util.rs

   1pub mod arc_cow;
   2pub mod archive;
   3pub mod command;
   4pub mod fs;
   5pub mod markdown;
   6pub mod paths;
   7pub mod serde;
   8pub mod size;
   9#[cfg(any(test, feature = "test-support"))]
  10pub mod test;
  11pub mod time;
  12
  13use anyhow::Result;
  14use futures::Future;
  15use itertools::Either;
  16use regex::Regex;
  17use std::sync::{LazyLock, OnceLock};
  18use std::{
  19    borrow::Cow,
  20    cmp::{self, Ordering},
  21    env,
  22    ops::{AddAssign, Range, RangeInclusive},
  23    panic::Location,
  24    pin::Pin,
  25    task::{Context, Poll},
  26    time::Instant,
  27};
  28use unicase::UniCase;
  29
  30#[cfg(unix)]
  31use anyhow::Context as _;
  32
  33pub use take_until::*;
  34#[cfg(any(test, feature = "test-support"))]
  35pub use util_macros::{line_endings, separator, uri};
  36
  37#[macro_export]
  38macro_rules! debug_panic {
  39    ( $($fmt_arg:tt)* ) => {
  40        if cfg!(debug_assertions) {
  41            panic!( $($fmt_arg)* );
  42        } else {
  43            let backtrace = std::backtrace::Backtrace::capture();
  44            log::error!("{}\n{:?}", format_args!($($fmt_arg)*), backtrace);
  45        }
  46    };
  47}
  48
  49/// A macro to add "C:" to the beginning of a path literal on Windows, and replace all
  50/// the separator from `/` to `\`.
  51/// But on non-Windows platforms, it will return the path literal as is.
  52///
  53/// # Examples
  54/// ```rust
  55/// use util::path;
  56///
  57/// let path = path!("/Users/user/file.txt");
  58/// #[cfg(target_os = "windows")]
  59/// assert_eq!(path, "C:\\Users\\user\\file.txt");
  60/// #[cfg(not(target_os = "windows"))]
  61/// assert_eq!(path, "/Users/user/file.txt");
  62/// ```
  63#[cfg(all(any(test, feature = "test-support"), target_os = "windows"))]
  64#[macro_export]
  65macro_rules! path {
  66    ($path:literal) => {
  67        concat!("C:", util::separator!($path))
  68    };
  69}
  70
  71/// A macro to add "C:" to the beginning of a path literal on Windows, and replace all
  72/// the separator from `/` to `\`.
  73/// But on non-Windows platforms, it will return the path literal as is.
  74///
  75/// # Examples
  76/// ```rust
  77/// use util::path;
  78///
  79/// let path = path!("/Users/user/file.txt");
  80/// #[cfg(target_os = "windows")]
  81/// assert_eq!(path, "C:\\Users\\user\\file.txt");
  82/// #[cfg(not(target_os = "windows"))]
  83/// assert_eq!(path, "/Users/user/file.txt");
  84/// ```
  85#[cfg(all(any(test, feature = "test-support"), not(target_os = "windows")))]
  86#[macro_export]
  87macro_rules! path {
  88    ($path:literal) => {
  89        $path
  90    };
  91}
  92
  93pub fn truncate(s: &str, max_chars: usize) -> &str {
  94    match s.char_indices().nth(max_chars) {
  95        None => s,
  96        Some((idx, _)) => &s[..idx],
  97    }
  98}
  99
 100/// Removes characters from the end of the string if its length is greater than `max_chars` and
 101/// appends "..." to the string. Returns string unchanged if its length is smaller than max_chars.
 102pub fn truncate_and_trailoff(s: &str, max_chars: usize) -> String {
 103    debug_assert!(max_chars >= 5);
 104
 105    // If the string's byte length is <= max_chars, walking the string can be skipped since the
 106    // number of chars is <= the number of bytes.
 107    if s.len() <= max_chars {
 108        return s.to_string();
 109    }
 110    let truncation_ix = s.char_indices().map(|(i, _)| i).nth(max_chars);
 111    match truncation_ix {
 112        Some(index) => s[..index].to_string() + "",
 113        _ => s.to_string(),
 114    }
 115}
 116
 117/// Removes characters from the front of the string if its length is greater than `max_chars` and
 118/// prepends the string with "...". Returns string unchanged if its length is smaller than max_chars.
 119pub fn truncate_and_remove_front(s: &str, max_chars: usize) -> String {
 120    debug_assert!(max_chars >= 5);
 121
 122    // If the string's byte length is <= max_chars, walking the string can be skipped since the
 123    // number of chars is <= the number of bytes.
 124    if s.len() <= max_chars {
 125        return s.to_string();
 126    }
 127    let suffix_char_length = max_chars.saturating_sub(1);
 128    let truncation_ix = s
 129        .char_indices()
 130        .map(|(i, _)| i)
 131        .nth_back(suffix_char_length);
 132    match truncation_ix {
 133        Some(index) if index > 0 => "".to_string() + &s[index..],
 134        _ => s.to_string(),
 135    }
 136}
 137
 138/// Takes only `max_lines` from the string and, if there were more than `max_lines-1`, appends a
 139/// a newline and "..." to the string, so that `max_lines` are returned.
 140/// Returns string unchanged if its length is smaller than max_lines.
 141pub fn truncate_lines_and_trailoff(s: &str, max_lines: usize) -> String {
 142    let mut lines = s.lines().take(max_lines).collect::<Vec<_>>();
 143    if lines.len() > max_lines - 1 {
 144        lines.pop();
 145        lines.join("\n") + "\n"
 146    } else {
 147        lines.join("\n")
 148    }
 149}
 150
 151/// Truncates the string at a character boundary, such that the result is less than `max_bytes` in
 152/// length.
 153pub fn truncate_to_byte_limit(s: &str, max_bytes: usize) -> &str {
 154    if s.len() < max_bytes {
 155        return s;
 156    }
 157
 158    for i in (0..max_bytes).rev() {
 159        if s.is_char_boundary(i) {
 160            return &s[..i];
 161        }
 162    }
 163
 164    ""
 165}
 166
 167/// Takes a prefix of complete lines which fit within the byte limit. If the first line is longer
 168/// than the limit, truncates at a character boundary.
 169pub fn truncate_lines_to_byte_limit(s: &str, max_bytes: usize) -> &str {
 170    if s.len() < max_bytes {
 171        return s;
 172    }
 173
 174    for i in (0..max_bytes).rev() {
 175        if s.is_char_boundary(i) {
 176            if s.as_bytes()[i] == b'\n' {
 177                // Since the i-th character is \n, valid to slice at i + 1.
 178                return &s[..i + 1];
 179            }
 180        }
 181    }
 182
 183    truncate_to_byte_limit(s, max_bytes)
 184}
 185
 186#[test]
 187fn test_truncate_lines_to_byte_limit() {
 188    let text = "Line 1\nLine 2\nLine 3\nLine 4";
 189
 190    // Limit that includes all lines
 191    assert_eq!(truncate_lines_to_byte_limit(text, 100), text);
 192
 193    // Exactly the first line
 194    assert_eq!(truncate_lines_to_byte_limit(text, 7), "Line 1\n");
 195
 196    // Limit between lines
 197    assert_eq!(truncate_lines_to_byte_limit(text, 13), "Line 1\n");
 198    assert_eq!(truncate_lines_to_byte_limit(text, 20), "Line 1\nLine 2\n");
 199
 200    // Limit before first newline
 201    assert_eq!(truncate_lines_to_byte_limit(text, 6), "Line ");
 202
 203    // Test with non-ASCII characters
 204    let text_utf8 = "Line 1\nLíne 2\nLine 3";
 205    assert_eq!(
 206        truncate_lines_to_byte_limit(text_utf8, 15),
 207        "Line 1\nLíne 2\n"
 208    );
 209}
 210
 211pub fn post_inc<T: From<u8> + AddAssign<T> + Copy>(value: &mut T) -> T {
 212    let prev = *value;
 213    *value += T::from(1);
 214    prev
 215}
 216
 217/// Extend a sorted vector with a sorted sequence of items, maintaining the vector's sort order and
 218/// enforcing a maximum length. This also de-duplicates items. Sort the items according to the given callback. Before calling this,
 219/// both `vec` and `new_items` should already be sorted according to the `cmp` comparator.
 220pub fn extend_sorted<T, I, F>(vec: &mut Vec<T>, new_items: I, limit: usize, mut cmp: F)
 221where
 222    I: IntoIterator<Item = T>,
 223    F: FnMut(&T, &T) -> Ordering,
 224{
 225    let mut start_index = 0;
 226    for new_item in new_items {
 227        if let Err(i) = vec[start_index..].binary_search_by(|m| cmp(m, &new_item)) {
 228            let index = start_index + i;
 229            if vec.len() < limit {
 230                vec.insert(index, new_item);
 231            } else if index < vec.len() {
 232                vec.pop();
 233                vec.insert(index, new_item);
 234            }
 235            start_index = index;
 236        }
 237    }
 238}
 239
 240pub fn truncate_to_bottom_n_sorted_by<T, F>(items: &mut Vec<T>, limit: usize, compare: &F)
 241where
 242    F: Fn(&T, &T) -> Ordering,
 243{
 244    if limit == 0 {
 245        items.truncate(0);
 246    }
 247    if items.len() <= limit {
 248        items.sort_by(compare);
 249        return;
 250    }
 251    // When limit is near to items.len() it may be more efficient to sort the whole list and
 252    // truncate, rather than always doing selection first as is done below. It's hard to analyze
 253    // where the threshold for this should be since the quickselect style algorithm used by
 254    // `select_nth_unstable_by` makes the prefix partially sorted, and so its work is not wasted -
 255    // the expected number of comparisons needed by `sort_by` is less than it is for some arbitrary
 256    // unsorted input.
 257    items.select_nth_unstable_by(limit, compare);
 258    items.truncate(limit);
 259    items.sort_by(compare);
 260}
 261
 262#[cfg(unix)]
 263fn load_shell_from_passwd() -> Result<()> {
 264    let buflen = match unsafe { libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) } {
 265        n if n < 0 => 1024,
 266        n => n as usize,
 267    };
 268    let mut buffer = Vec::with_capacity(buflen);
 269
 270    let mut pwd: std::mem::MaybeUninit<libc::passwd> = std::mem::MaybeUninit::uninit();
 271    let mut result: *mut libc::passwd = std::ptr::null_mut();
 272
 273    let uid = unsafe { libc::getuid() };
 274    let status = unsafe {
 275        libc::getpwuid_r(
 276            uid,
 277            pwd.as_mut_ptr(),
 278            buffer.as_mut_ptr() as *mut libc::c_char,
 279            buflen,
 280            &mut result,
 281        )
 282    };
 283    let entry = unsafe { pwd.assume_init() };
 284
 285    anyhow::ensure!(
 286        status == 0,
 287        "call to getpwuid_r failed. uid: {}, status: {}",
 288        uid,
 289        status
 290    );
 291    anyhow::ensure!(!result.is_null(), "passwd entry for uid {} not found", uid);
 292    anyhow::ensure!(
 293        entry.pw_uid == uid,
 294        "passwd entry has different uid ({}) than getuid ({}) returned",
 295        entry.pw_uid,
 296        uid,
 297    );
 298
 299    let shell = unsafe { std::ffi::CStr::from_ptr(entry.pw_shell).to_str().unwrap() };
 300    if env::var("SHELL").map_or(true, |shell_env| shell_env != shell) {
 301        log::info!(
 302            "updating SHELL environment variable to value from passwd entry: {:?}",
 303            shell,
 304        );
 305        unsafe { env::set_var("SHELL", shell) };
 306    }
 307
 308    Ok(())
 309}
 310
 311#[cfg(unix)]
 312pub fn load_login_shell_environment() -> Result<()> {
 313    load_shell_from_passwd().log_err();
 314
 315    let marker = "ZED_LOGIN_SHELL_START";
 316    let shell = env::var("SHELL").context(
 317        "SHELL environment variable is not assigned so we can't source login environment variables",
 318    )?;
 319
 320    // If possible, we want to `cd` in the user's `$HOME` to trigger programs
 321    // such as direnv, asdf, mise, ... to adjust the PATH. These tools often hook
 322    // into shell's `cd` command (and hooks) to manipulate env.
 323    // We do this so that we get the env a user would have when spawning a shell
 324    // in home directory.
 325    let shell_cmd_prefix = std::env::var_os("HOME")
 326        .and_then(|home| home.into_string().ok())
 327        .map(|home| format!("cd '{home}';"));
 328
 329    let shell_cmd = format!(
 330        "{}printf '%s' {marker}; /usr/bin/env;",
 331        shell_cmd_prefix.as_deref().unwrap_or("")
 332    );
 333
 334    let output = set_pre_exec_to_start_new_session(
 335        std::process::Command::new(&shell).args(["-l", "-i", "-c", &shell_cmd]),
 336    )
 337    .output()
 338    .context("failed to spawn login shell to source login environment variables")?;
 339    anyhow::ensure!(output.status.success(), "login shell exited with error");
 340
 341    let stdout = String::from_utf8_lossy(&output.stdout);
 342
 343    if let Some(env_output_start) = stdout.find(marker) {
 344        let env_output = &stdout[env_output_start + marker.len()..];
 345
 346        parse_env_output(env_output, |key, value| unsafe { env::set_var(key, value) });
 347
 348        log::info!(
 349            "set environment variables from shell:{}, path:{}",
 350            shell,
 351            env::var("PATH").unwrap_or_default(),
 352        );
 353    }
 354
 355    Ok(())
 356}
 357
 358/// Configures the process to start a new session, to prevent interactive shells from taking control
 359/// of the terminal.
 360///
 361/// For more details: https://registerspill.thorstenball.com/p/how-to-lose-control-of-your-shell
 362pub fn set_pre_exec_to_start_new_session(
 363    command: &mut std::process::Command,
 364) -> &mut std::process::Command {
 365    // safety: code in pre_exec should be signal safe.
 366    // https://man7.org/linux/man-pages/man7/signal-safety.7.html
 367    #[cfg(not(target_os = "windows"))]
 368    unsafe {
 369        use std::os::unix::process::CommandExt;
 370        command.pre_exec(|| {
 371            libc::setsid();
 372            Ok(())
 373        });
 374    };
 375    command
 376}
 377
 378/// Parse the result of calling `usr/bin/env` with no arguments
 379pub fn parse_env_output(env: &str, mut f: impl FnMut(String, String)) {
 380    let mut current_key: Option<String> = None;
 381    let mut current_value: Option<String> = None;
 382
 383    for line in env.split_terminator('\n') {
 384        if let Some(separator_index) = line.find('=') {
 385            if !line[..separator_index].is_empty() {
 386                if let Some((key, value)) = Option::zip(current_key.take(), current_value.take()) {
 387                    f(key, value)
 388                }
 389                current_key = Some(line[..separator_index].to_string());
 390                current_value = Some(line[separator_index + 1..].to_string());
 391                continue;
 392            };
 393        }
 394        if let Some(value) = current_value.as_mut() {
 395            value.push('\n');
 396            value.push_str(line);
 397        }
 398    }
 399    if let Some((key, value)) = Option::zip(current_key.take(), current_value.take()) {
 400        f(key, value)
 401    }
 402}
 403
 404pub fn merge_json_lenient_value_into(
 405    source: serde_json_lenient::Value,
 406    target: &mut serde_json_lenient::Value,
 407) {
 408    match (source, target) {
 409        (serde_json_lenient::Value::Object(source), serde_json_lenient::Value::Object(target)) => {
 410            for (key, value) in source {
 411                if let Some(target) = target.get_mut(&key) {
 412                    merge_json_lenient_value_into(value, target);
 413                } else {
 414                    target.insert(key, value);
 415                }
 416            }
 417        }
 418
 419        (serde_json_lenient::Value::Array(source), serde_json_lenient::Value::Array(target)) => {
 420            for value in source {
 421                target.push(value);
 422            }
 423        }
 424
 425        (source, target) => *target = source,
 426    }
 427}
 428
 429pub fn merge_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
 430    use serde_json::Value;
 431
 432    match (source, target) {
 433        (Value::Object(source), Value::Object(target)) => {
 434            for (key, value) in source {
 435                if let Some(target) = target.get_mut(&key) {
 436                    merge_json_value_into(value, target);
 437                } else {
 438                    target.insert(key, value);
 439                }
 440            }
 441        }
 442
 443        (Value::Array(source), Value::Array(target)) => {
 444            for value in source {
 445                target.push(value);
 446            }
 447        }
 448
 449        (source, target) => *target = source,
 450    }
 451}
 452
 453pub fn merge_non_null_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
 454    use serde_json::Value;
 455    if let Value::Object(source_object) = source {
 456        let target_object = if let Value::Object(target) = target {
 457            target
 458        } else {
 459            *target = Value::Object(Default::default());
 460            target.as_object_mut().unwrap()
 461        };
 462        for (key, value) in source_object {
 463            if let Some(target) = target_object.get_mut(&key) {
 464                merge_non_null_json_value_into(value, target);
 465            } else if !value.is_null() {
 466                target_object.insert(key, value);
 467            }
 468        }
 469    } else if !source.is_null() {
 470        *target = source
 471    }
 472}
 473
 474pub fn measure<R>(label: &str, f: impl FnOnce() -> R) -> R {
 475    static ZED_MEASUREMENTS: OnceLock<bool> = OnceLock::new();
 476    let zed_measurements = ZED_MEASUREMENTS.get_or_init(|| {
 477        env::var("ZED_MEASUREMENTS")
 478            .map(|measurements| measurements == "1" || measurements == "true")
 479            .unwrap_or(false)
 480    });
 481
 482    if *zed_measurements {
 483        let start = Instant::now();
 484        let result = f();
 485        let elapsed = start.elapsed();
 486        eprintln!("{}: {:?}", label, elapsed);
 487        result
 488    } else {
 489        f()
 490    }
 491}
 492
 493pub fn iterate_expanded_and_wrapped_usize_range(
 494    range: Range<usize>,
 495    additional_before: usize,
 496    additional_after: usize,
 497    wrap_length: usize,
 498) -> impl Iterator<Item = usize> {
 499    let start_wraps = range.start < additional_before;
 500    let end_wraps = wrap_length < range.end + additional_after;
 501    if start_wraps && end_wraps {
 502        Either::Left(0..wrap_length)
 503    } else if start_wraps {
 504        let wrapped_start = (range.start + wrap_length).saturating_sub(additional_before);
 505        if wrapped_start <= range.end {
 506            Either::Left(0..wrap_length)
 507        } else {
 508            Either::Right((0..range.end + additional_after).chain(wrapped_start..wrap_length))
 509        }
 510    } else if end_wraps {
 511        let wrapped_end = range.end + additional_after - wrap_length;
 512        if range.start <= wrapped_end {
 513            Either::Left(0..wrap_length)
 514        } else {
 515            Either::Right((0..wrapped_end).chain(range.start - additional_before..wrap_length))
 516        }
 517    } else {
 518        Either::Left((range.start - additional_before)..(range.end + additional_after))
 519    }
 520}
 521
 522#[cfg(target_os = "windows")]
 523pub fn get_windows_system_shell() -> String {
 524    use std::path::PathBuf;
 525
 526    fn find_pwsh_in_programfiles(find_alternate: bool, find_preview: bool) -> Option<PathBuf> {
 527        #[cfg(target_pointer_width = "64")]
 528        let env_var = if find_alternate {
 529            "ProgramFiles(x86)"
 530        } else {
 531            "ProgramFiles"
 532        };
 533
 534        #[cfg(target_pointer_width = "32")]
 535        let env_var = if find_alternate {
 536            "ProgramW6432"
 537        } else {
 538            "ProgramFiles"
 539        };
 540
 541        let install_base_dir = PathBuf::from(std::env::var_os(env_var)?).join("PowerShell");
 542        install_base_dir
 543            .read_dir()
 544            .ok()?
 545            .filter_map(Result::ok)
 546            .filter(|entry| matches!(entry.file_type(), Ok(ft) if ft.is_dir()))
 547            .filter_map(|entry| {
 548                let dir_name = entry.file_name();
 549                let dir_name = dir_name.to_string_lossy();
 550
 551                let version = if find_preview {
 552                    let dash_index = dir_name.find('-')?;
 553                    if &dir_name[dash_index + 1..] != "preview" {
 554                        return None;
 555                    };
 556                    dir_name[..dash_index].parse::<u32>().ok()?
 557                } else {
 558                    dir_name.parse::<u32>().ok()?
 559                };
 560
 561                let exe_path = entry.path().join("pwsh.exe");
 562                if exe_path.exists() {
 563                    Some((version, exe_path))
 564                } else {
 565                    None
 566                }
 567            })
 568            .max_by_key(|(version, _)| *version)
 569            .map(|(_, path)| path)
 570    }
 571
 572    fn find_pwsh_in_msix(find_preview: bool) -> Option<PathBuf> {
 573        let msix_app_dir =
 574            PathBuf::from(std::env::var_os("LOCALAPPDATA")?).join("Microsoft\\WindowsApps");
 575        if !msix_app_dir.exists() {
 576            return None;
 577        }
 578
 579        let prefix = if find_preview {
 580            "Microsoft.PowerShellPreview_"
 581        } else {
 582            "Microsoft.PowerShell_"
 583        };
 584        msix_app_dir
 585            .read_dir()
 586            .ok()?
 587            .filter_map(|entry| {
 588                let entry = entry.ok()?;
 589                if !matches!(entry.file_type(), Ok(ft) if ft.is_dir()) {
 590                    return None;
 591                }
 592
 593                if !entry.file_name().to_string_lossy().starts_with(prefix) {
 594                    return None;
 595                }
 596
 597                let exe_path = entry.path().join("pwsh.exe");
 598                exe_path.exists().then_some(exe_path)
 599            })
 600            .next()
 601    }
 602
 603    fn find_pwsh_in_scoop() -> Option<PathBuf> {
 604        let pwsh_exe =
 605            PathBuf::from(std::env::var_os("USERPROFILE")?).join("scoop\\shims\\pwsh.exe");
 606        pwsh_exe.exists().then_some(pwsh_exe)
 607    }
 608
 609    static SYSTEM_SHELL: LazyLock<String> = LazyLock::new(|| {
 610        find_pwsh_in_programfiles(false, false)
 611            .or_else(|| find_pwsh_in_programfiles(true, false))
 612            .or_else(|| find_pwsh_in_msix(false))
 613            .or_else(|| find_pwsh_in_programfiles(false, true))
 614            .or_else(|| find_pwsh_in_msix(true))
 615            .or_else(|| find_pwsh_in_programfiles(true, true))
 616            .or_else(find_pwsh_in_scoop)
 617            .map(|p| p.to_string_lossy().to_string())
 618            .unwrap_or("powershell.exe".to_string())
 619    });
 620
 621    (*SYSTEM_SHELL).clone()
 622}
 623
 624pub trait ResultExt<E> {
 625    type Ok;
 626
 627    fn log_err(self) -> Option<Self::Ok>;
 628    /// Assert that this result should never be an error in development or tests.
 629    fn debug_assert_ok(self, reason: &str) -> Self;
 630    fn warn_on_err(self) -> Option<Self::Ok>;
 631    fn log_with_level(self, level: log::Level) -> Option<Self::Ok>;
 632    fn anyhow(self) -> anyhow::Result<Self::Ok>
 633    where
 634        E: Into<anyhow::Error>;
 635}
 636
 637impl<T, E> ResultExt<E> for Result<T, E>
 638where
 639    E: std::fmt::Debug,
 640{
 641    type Ok = T;
 642
 643    #[track_caller]
 644    fn log_err(self) -> Option<T> {
 645        self.log_with_level(log::Level::Error)
 646    }
 647
 648    #[track_caller]
 649    fn debug_assert_ok(self, reason: &str) -> Self {
 650        if let Err(error) = &self {
 651            debug_panic!("{reason} - {error:?}");
 652        }
 653        self
 654    }
 655
 656    #[track_caller]
 657    fn warn_on_err(self) -> Option<T> {
 658        self.log_with_level(log::Level::Warn)
 659    }
 660
 661    #[track_caller]
 662    fn log_with_level(self, level: log::Level) -> Option<T> {
 663        match self {
 664            Ok(value) => Some(value),
 665            Err(error) => {
 666                log_error_with_caller(*Location::caller(), error, level);
 667                None
 668            }
 669        }
 670    }
 671
 672    fn anyhow(self) -> anyhow::Result<T>
 673    where
 674        E: Into<anyhow::Error>,
 675    {
 676        self.map_err(Into::into)
 677    }
 678}
 679
 680fn log_error_with_caller<E>(caller: core::panic::Location<'_>, error: E, level: log::Level)
 681where
 682    E: std::fmt::Debug,
 683{
 684    #[cfg(not(target_os = "windows"))]
 685    let file = caller.file();
 686    #[cfg(target_os = "windows")]
 687    let file = caller.file().replace('\\', "/");
 688    // In this codebase, the first segment of the file path is
 689    // the 'crates' folder, followed by the crate name.
 690    let target = file.split('/').nth(1);
 691
 692    log::logger().log(
 693        &log::Record::builder()
 694            .target(target.unwrap_or(""))
 695            .module_path(target)
 696            .args(format_args!("{:?}", error))
 697            .file(Some(caller.file()))
 698            .line(Some(caller.line()))
 699            .level(level)
 700            .build(),
 701    );
 702}
 703
 704pub fn log_err<E: std::fmt::Debug>(error: &E) {
 705    log_error_with_caller(*Location::caller(), error, log::Level::Warn);
 706}
 707
 708pub trait TryFutureExt {
 709    fn log_err(self) -> LogErrorFuture<Self>
 710    where
 711        Self: Sized;
 712
 713    fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
 714    where
 715        Self: Sized;
 716
 717    fn warn_on_err(self) -> LogErrorFuture<Self>
 718    where
 719        Self: Sized;
 720    fn unwrap(self) -> UnwrapFuture<Self>
 721    where
 722        Self: Sized;
 723}
 724
 725impl<F, T, E> TryFutureExt for F
 726where
 727    F: Future<Output = Result<T, E>>,
 728    E: std::fmt::Debug,
 729{
 730    #[track_caller]
 731    fn log_err(self) -> LogErrorFuture<Self>
 732    where
 733        Self: Sized,
 734    {
 735        let location = Location::caller();
 736        LogErrorFuture(self, log::Level::Error, *location)
 737    }
 738
 739    fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
 740    where
 741        Self: Sized,
 742    {
 743        LogErrorFuture(self, log::Level::Error, location)
 744    }
 745
 746    #[track_caller]
 747    fn warn_on_err(self) -> LogErrorFuture<Self>
 748    where
 749        Self: Sized,
 750    {
 751        let location = Location::caller();
 752        LogErrorFuture(self, log::Level::Warn, *location)
 753    }
 754
 755    fn unwrap(self) -> UnwrapFuture<Self>
 756    where
 757        Self: Sized,
 758    {
 759        UnwrapFuture(self)
 760    }
 761}
 762
 763#[must_use]
 764pub struct LogErrorFuture<F>(F, log::Level, core::panic::Location<'static>);
 765
 766impl<F, T, E> Future for LogErrorFuture<F>
 767where
 768    F: Future<Output = Result<T, E>>,
 769    E: std::fmt::Debug,
 770{
 771    type Output = Option<T>;
 772
 773    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
 774        let level = self.1;
 775        let location = self.2;
 776        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
 777        match inner.poll(cx) {
 778            Poll::Ready(output) => Poll::Ready(match output {
 779                Ok(output) => Some(output),
 780                Err(error) => {
 781                    log_error_with_caller(location, error, level);
 782                    None
 783                }
 784            }),
 785            Poll::Pending => Poll::Pending,
 786        }
 787    }
 788}
 789
 790pub struct UnwrapFuture<F>(F);
 791
 792impl<F, T, E> Future for UnwrapFuture<F>
 793where
 794    F: Future<Output = Result<T, E>>,
 795    E: std::fmt::Debug,
 796{
 797    type Output = T;
 798
 799    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
 800        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
 801        match inner.poll(cx) {
 802            Poll::Ready(result) => Poll::Ready(result.unwrap()),
 803            Poll::Pending => Poll::Pending,
 804        }
 805    }
 806}
 807
 808pub struct Deferred<F: FnOnce()>(Option<F>);
 809
 810impl<F: FnOnce()> Deferred<F> {
 811    /// Drop without running the deferred function.
 812    pub fn abort(mut self) {
 813        self.0.take();
 814    }
 815}
 816
 817impl<F: FnOnce()> Drop for Deferred<F> {
 818    fn drop(&mut self) {
 819        if let Some(f) = self.0.take() {
 820            f()
 821        }
 822    }
 823}
 824
 825/// Run the given function when the returned value is dropped (unless it's cancelled).
 826#[must_use]
 827pub fn defer<F: FnOnce()>(f: F) -> Deferred<F> {
 828    Deferred(Some(f))
 829}
 830
 831#[cfg(any(test, feature = "test-support"))]
 832mod rng {
 833    use rand::{Rng, seq::SliceRandom};
 834    pub struct RandomCharIter<T: Rng> {
 835        rng: T,
 836        simple_text: bool,
 837    }
 838
 839    impl<T: Rng> RandomCharIter<T> {
 840        pub fn new(rng: T) -> Self {
 841            Self {
 842                rng,
 843                simple_text: std::env::var("SIMPLE_TEXT").map_or(false, |v| !v.is_empty()),
 844            }
 845        }
 846
 847        pub fn with_simple_text(mut self) -> Self {
 848            self.simple_text = true;
 849            self
 850        }
 851    }
 852
 853    impl<T: Rng> Iterator for RandomCharIter<T> {
 854        type Item = char;
 855
 856        fn next(&mut self) -> Option<Self::Item> {
 857            if self.simple_text {
 858                return if self.rng.gen_range(0..100) < 5 {
 859                    Some('\n')
 860                } else {
 861                    Some(self.rng.gen_range(b'a'..b'z' + 1).into())
 862                };
 863            }
 864
 865            match self.rng.gen_range(0..100) {
 866                // whitespace
 867                0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.rng).copied(),
 868                // two-byte greek letters
 869                20..=32 => char::from_u32(self.rng.gen_range(('α' as u32)..('ω' as u32 + 1))),
 870                // // three-byte characters
 871                33..=45 => ['✋', '✅', '❌', '❎', '⭐']
 872                    .choose(&mut self.rng)
 873                    .copied(),
 874                // // four-byte characters
 875                46..=58 => ['🍐', '🏀', '🍗', '🎉'].choose(&mut self.rng).copied(),
 876                // ascii letters
 877                _ => Some(self.rng.gen_range(b'a'..b'z' + 1).into()),
 878            }
 879        }
 880    }
 881}
 882#[cfg(any(test, feature = "test-support"))]
 883pub use rng::RandomCharIter;
 884/// Get an embedded file as a string.
 885pub fn asset_str<A: rust_embed::RustEmbed>(path: &str) -> Cow<'static, str> {
 886    match A::get(path).expect(path).data {
 887        Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()),
 888        Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()),
 889    }
 890}
 891
 892/// Expands to an immediately-invoked function expression. Good for using the ? operator
 893/// in functions which do not return an Option or Result.
 894///
 895/// Accepts a normal block, an async block, or an async move block.
 896#[macro_export]
 897macro_rules! maybe {
 898    ($block:block) => {
 899        (|| $block)()
 900    };
 901    (async $block:block) => {
 902        (|| async $block)()
 903    };
 904    (async move $block:block) => {
 905        (|| async move $block)()
 906    };
 907}
 908
 909pub trait RangeExt<T> {
 910    fn sorted(&self) -> Self;
 911    fn to_inclusive(&self) -> RangeInclusive<T>;
 912    fn overlaps(&self, other: &Range<T>) -> bool;
 913    fn contains_inclusive(&self, other: &Range<T>) -> bool;
 914}
 915
 916impl<T: Ord + Clone> RangeExt<T> for Range<T> {
 917    fn sorted(&self) -> Self {
 918        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
 919    }
 920
 921    fn to_inclusive(&self) -> RangeInclusive<T> {
 922        self.start.clone()..=self.end.clone()
 923    }
 924
 925    fn overlaps(&self, other: &Range<T>) -> bool {
 926        self.start < other.end && other.start < self.end
 927    }
 928
 929    fn contains_inclusive(&self, other: &Range<T>) -> bool {
 930        self.start <= other.start && other.end <= self.end
 931    }
 932}
 933
 934impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
 935    fn sorted(&self) -> Self {
 936        cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
 937    }
 938
 939    fn to_inclusive(&self) -> RangeInclusive<T> {
 940        self.clone()
 941    }
 942
 943    fn overlaps(&self, other: &Range<T>) -> bool {
 944        self.start() < &other.end && &other.start <= self.end()
 945    }
 946
 947    fn contains_inclusive(&self, other: &Range<T>) -> bool {
 948        self.start() <= &other.start && &other.end <= self.end()
 949    }
 950}
 951
 952/// A way to sort strings with starting numbers numerically first, falling back to alphanumeric one,
 953/// case-insensitive.
 954///
 955/// This is useful for turning regular alphanumerically sorted sequences as `1-abc, 10, 11-def, .., 2, 21-abc`
 956/// into `1-abc, 2, 10, 11-def, .., 21-abc`
 957#[derive(Debug, PartialEq, Eq)]
 958pub struct NumericPrefixWithSuffix<'a>(Option<u64>, &'a str);
 959
 960impl<'a> NumericPrefixWithSuffix<'a> {
 961    pub fn from_numeric_prefixed_str(str: &'a str) -> Self {
 962        let i = str.chars().take_while(|c| c.is_ascii_digit()).count();
 963        let (prefix, remainder) = str.split_at(i);
 964
 965        let prefix = prefix.parse().ok();
 966        Self(prefix, remainder)
 967    }
 968}
 969
 970/// When dealing with equality, we need to consider the case of the strings to achieve strict equality
 971/// to handle cases like "a" < "A" instead of "a" == "A".
 972impl Ord for NumericPrefixWithSuffix<'_> {
 973    fn cmp(&self, other: &Self) -> Ordering {
 974        match (self.0, other.0) {
 975            (None, None) => UniCase::new(self.1)
 976                .cmp(&UniCase::new(other.1))
 977                .then_with(|| self.1.cmp(other.1).reverse()),
 978            (None, Some(_)) => Ordering::Greater,
 979            (Some(_), None) => Ordering::Less,
 980            (Some(a), Some(b)) => a.cmp(&b).then_with(|| {
 981                UniCase::new(self.1)
 982                    .cmp(&UniCase::new(other.1))
 983                    .then_with(|| self.1.cmp(other.1).reverse())
 984            }),
 985        }
 986    }
 987}
 988
 989impl PartialOrd for NumericPrefixWithSuffix<'_> {
 990    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
 991        Some(self.cmp(other))
 992    }
 993}
 994
 995/// Capitalizes the first character of a string.
 996///
 997/// This function takes a string slice as input and returns a new `String` with the first character
 998/// capitalized.
 999///
1000/// # Examples
1001///
1002/// ```
1003/// use util::capitalize;
1004///
1005/// assert_eq!(capitalize("hello"), "Hello");
1006/// assert_eq!(capitalize("WORLD"), "WORLD");
1007/// assert_eq!(capitalize(""), "");
1008/// ```
1009pub fn capitalize(str: &str) -> String {
1010    let mut chars = str.chars();
1011    match chars.next() {
1012        None => String::new(),
1013        Some(first_char) => first_char.to_uppercase().collect::<String>() + chars.as_str(),
1014    }
1015}
1016
1017fn emoji_regex() -> &'static Regex {
1018    static EMOJI_REGEX: LazyLock<Regex> =
1019        LazyLock::new(|| Regex::new("(\\p{Emoji}|\u{200D})").unwrap());
1020    &EMOJI_REGEX
1021}
1022
1023/// Returns true if the given string consists of emojis only.
1024/// E.g. "👨‍👩‍👧‍👧👋" will return true, but "👋!" will return false.
1025pub fn word_consists_of_emojis(s: &str) -> bool {
1026    let mut prev_end = 0;
1027    for capture in emoji_regex().find_iter(s) {
1028        if capture.start() != prev_end {
1029            return false;
1030        }
1031        prev_end = capture.end();
1032    }
1033    prev_end == s.len()
1034}
1035
1036pub fn default<D: Default>() -> D {
1037    Default::default()
1038}
1039
1040pub fn get_system_shell() -> String {
1041    #[cfg(target_os = "windows")]
1042    {
1043        get_windows_system_shell()
1044    }
1045
1046    #[cfg(not(target_os = "windows"))]
1047    {
1048        std::env::var("SHELL").unwrap_or("/bin/sh".to_string())
1049    }
1050}
1051
1052#[derive(Debug)]
1053pub enum ConnectionResult<O> {
1054    Timeout,
1055    ConnectionReset,
1056    Result(anyhow::Result<O>),
1057}
1058
1059impl<O> ConnectionResult<O> {
1060    pub fn into_response(self) -> anyhow::Result<O> {
1061        match self {
1062            ConnectionResult::Timeout => anyhow::bail!("Request timed out"),
1063            ConnectionResult::ConnectionReset => anyhow::bail!("Server reset the connection"),
1064            ConnectionResult::Result(r) => r,
1065        }
1066    }
1067}
1068
1069impl<O> From<anyhow::Result<O>> for ConnectionResult<O> {
1070    fn from(result: anyhow::Result<O>) -> Self {
1071        ConnectionResult::Result(result)
1072    }
1073}
1074
1075#[cfg(test)]
1076mod tests {
1077    use super::*;
1078
1079    #[test]
1080    fn test_extend_sorted() {
1081        let mut vec = vec![];
1082
1083        extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
1084        assert_eq!(vec, &[21, 17, 13, 8, 1]);
1085
1086        extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
1087        assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
1088
1089        extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
1090        assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
1091    }
1092
1093    #[test]
1094    fn test_truncate_to_bottom_n_sorted_by() {
1095        let mut vec: Vec<u32> = vec![5, 2, 3, 4, 1];
1096        truncate_to_bottom_n_sorted_by(&mut vec, 10, &u32::cmp);
1097        assert_eq!(vec, &[1, 2, 3, 4, 5]);
1098
1099        vec = vec![5, 2, 3, 4, 1];
1100        truncate_to_bottom_n_sorted_by(&mut vec, 5, &u32::cmp);
1101        assert_eq!(vec, &[1, 2, 3, 4, 5]);
1102
1103        vec = vec![5, 2, 3, 4, 1];
1104        truncate_to_bottom_n_sorted_by(&mut vec, 4, &u32::cmp);
1105        assert_eq!(vec, &[1, 2, 3, 4]);
1106
1107        vec = vec![5, 2, 3, 4, 1];
1108        truncate_to_bottom_n_sorted_by(&mut vec, 1, &u32::cmp);
1109        assert_eq!(vec, &[1]);
1110
1111        vec = vec![5, 2, 3, 4, 1];
1112        truncate_to_bottom_n_sorted_by(&mut vec, 0, &u32::cmp);
1113        assert!(vec.is_empty());
1114    }
1115
1116    #[test]
1117    fn test_iife() {
1118        fn option_returning_function() -> Option<()> {
1119            None
1120        }
1121
1122        let foo = maybe!({
1123            option_returning_function()?;
1124            Some(())
1125        });
1126
1127        assert_eq!(foo, None);
1128    }
1129
1130    #[test]
1131    fn test_truncate_and_trailoff() {
1132        assert_eq!(truncate_and_trailoff("", 5), "");
1133        assert_eq!(truncate_and_trailoff("aaaaaa", 7), "aaaaaa");
1134        assert_eq!(truncate_and_trailoff("aaaaaa", 6), "aaaaaa");
1135        assert_eq!(truncate_and_trailoff("aaaaaa", 5), "aaaaa…");
1136        assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
1137        assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
1138        assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèè…");
1139    }
1140
1141    #[test]
1142    fn test_truncate_and_remove_front() {
1143        assert_eq!(truncate_and_remove_front("", 5), "");
1144        assert_eq!(truncate_and_remove_front("aaaaaa", 7), "aaaaaa");
1145        assert_eq!(truncate_and_remove_front("aaaaaa", 6), "aaaaaa");
1146        assert_eq!(truncate_and_remove_front("aaaaaa", 5), "…aaaaa");
1147        assert_eq!(truncate_and_remove_front("èèèèèè", 7), "èèèèèè");
1148        assert_eq!(truncate_and_remove_front("èèèèèè", 6), "èèèèèè");
1149        assert_eq!(truncate_and_remove_front("èèèèèè", 5), "…èèèèè");
1150    }
1151
1152    #[test]
1153    fn test_numeric_prefix_str_method() {
1154        let target = "1a";
1155        assert_eq!(
1156            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1157            NumericPrefixWithSuffix(Some(1), "a")
1158        );
1159
1160        let target = "12ab";
1161        assert_eq!(
1162            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1163            NumericPrefixWithSuffix(Some(12), "ab")
1164        );
1165
1166        let target = "12_ab";
1167        assert_eq!(
1168            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1169            NumericPrefixWithSuffix(Some(12), "_ab")
1170        );
1171
1172        let target = "1_2ab";
1173        assert_eq!(
1174            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1175            NumericPrefixWithSuffix(Some(1), "_2ab")
1176        );
1177
1178        let target = "1.2";
1179        assert_eq!(
1180            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1181            NumericPrefixWithSuffix(Some(1), ".2")
1182        );
1183
1184        let target = "1.2_a";
1185        assert_eq!(
1186            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1187            NumericPrefixWithSuffix(Some(1), ".2_a")
1188        );
1189
1190        let target = "12.2_a";
1191        assert_eq!(
1192            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1193            NumericPrefixWithSuffix(Some(12), ".2_a")
1194        );
1195
1196        let target = "12a.2_a";
1197        assert_eq!(
1198            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1199            NumericPrefixWithSuffix(Some(12), "a.2_a")
1200        );
1201    }
1202
1203    #[test]
1204    fn test_numeric_prefix_with_suffix() {
1205        let mut sorted = vec!["1-abc", "10", "11def", "2", "21-abc"];
1206        sorted.sort_by_key(|s| NumericPrefixWithSuffix::from_numeric_prefixed_str(s));
1207        assert_eq!(sorted, ["1-abc", "2", "10", "11def", "21-abc"]);
1208
1209        for numeric_prefix_less in ["numeric_prefix_less", "aaa", "~™£"] {
1210            assert_eq!(
1211                NumericPrefixWithSuffix::from_numeric_prefixed_str(numeric_prefix_less),
1212                NumericPrefixWithSuffix(None, numeric_prefix_less),
1213                "String without numeric prefix `{numeric_prefix_less}` should not be converted into NumericPrefixWithSuffix"
1214            )
1215        }
1216    }
1217
1218    #[test]
1219    fn test_word_consists_of_emojis() {
1220        let words_to_test = vec![
1221            ("👨‍👩‍👧‍👧👋🥒", true),
1222            ("👋", true),
1223            ("!👋", false),
1224            ("👋!", false),
1225            ("👋 ", false),
1226            (" 👋", false),
1227            ("Test", false),
1228        ];
1229
1230        for (text, expected_result) in words_to_test {
1231            assert_eq!(word_consists_of_emojis(text), expected_result);
1232        }
1233    }
1234
1235    #[test]
1236    fn test_truncate_lines_and_trailoff() {
1237        let text = r#"Line 1
1238Line 2
1239Line 3"#;
1240
1241        assert_eq!(
1242            truncate_lines_and_trailoff(text, 2),
1243            r#"Line 1
1244…"#
1245        );
1246
1247        assert_eq!(
1248            truncate_lines_and_trailoff(text, 3),
1249            r#"Line 1
1250Line 2
1251…"#
1252        );
1253
1254        assert_eq!(
1255            truncate_lines_and_trailoff(text, 4),
1256            r#"Line 1
1257Line 2
1258Line 3"#
1259        );
1260    }
1261
1262    #[test]
1263    fn test_iterate_expanded_and_wrapped_usize_range() {
1264        // Neither wrap
1265        assert_eq!(
1266            iterate_expanded_and_wrapped_usize_range(2..4, 1, 1, 8).collect::<Vec<usize>>(),
1267            (1..5).collect::<Vec<usize>>()
1268        );
1269        // Start wraps
1270        assert_eq!(
1271            iterate_expanded_and_wrapped_usize_range(2..4, 3, 1, 8).collect::<Vec<usize>>(),
1272            ((0..5).chain(7..8)).collect::<Vec<usize>>()
1273        );
1274        // Start wraps all the way around
1275        assert_eq!(
1276            iterate_expanded_and_wrapped_usize_range(2..4, 5, 1, 8).collect::<Vec<usize>>(),
1277            (0..8).collect::<Vec<usize>>()
1278        );
1279        // Start wraps all the way around and past 0
1280        assert_eq!(
1281            iterate_expanded_and_wrapped_usize_range(2..4, 10, 1, 8).collect::<Vec<usize>>(),
1282            (0..8).collect::<Vec<usize>>()
1283        );
1284        // End wraps
1285        assert_eq!(
1286            iterate_expanded_and_wrapped_usize_range(3..5, 1, 4, 8).collect::<Vec<usize>>(),
1287            (0..1).chain(2..8).collect::<Vec<usize>>()
1288        );
1289        // End wraps all the way around
1290        assert_eq!(
1291            iterate_expanded_and_wrapped_usize_range(3..5, 1, 5, 8).collect::<Vec<usize>>(),
1292            (0..8).collect::<Vec<usize>>()
1293        );
1294        // End wraps all the way around and past the end
1295        assert_eq!(
1296            iterate_expanded_and_wrapped_usize_range(3..5, 1, 10, 8).collect::<Vec<usize>>(),
1297            (0..8).collect::<Vec<usize>>()
1298        );
1299        // Both start and end wrap
1300        assert_eq!(
1301            iterate_expanded_and_wrapped_usize_range(3..5, 4, 4, 8).collect::<Vec<usize>>(),
1302            (0..8).collect::<Vec<usize>>()
1303        );
1304    }
1305}