util.rs

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