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(shell_kind: shell::ShellKind) -> 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(shell_kind)
 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())
 358        .await
 359        .with_context(|| format!("capturing environment with {:?}", get_system_shell()))?
 360    {
 361        unsafe { env::set_var(&name, &value) };
 362    }
 363
 364    log::info!(
 365        "set environment variables from shell:{}, path:{}",
 366        std::env::var("SHELL").unwrap_or_default(),
 367        std::env::var("PATH").unwrap_or_default(),
 368    );
 369
 370    Ok(())
 371}
 372
 373/// Configures the process to start a new session, to prevent interactive shells from taking control
 374/// of the terminal.
 375///
 376/// For more details: <https://registerspill.thorstenball.com/p/how-to-lose-control-of-your-shell>
 377pub fn set_pre_exec_to_start_new_session(
 378    command: &mut std::process::Command,
 379) -> &mut std::process::Command {
 380    // safety: code in pre_exec should be signal safe.
 381    // https://man7.org/linux/man-pages/man7/signal-safety.7.html
 382    #[cfg(not(target_os = "windows"))]
 383    unsafe {
 384        use std::os::unix::process::CommandExt;
 385        command.pre_exec(|| {
 386            libc::setsid();
 387            Ok(())
 388        });
 389    };
 390    command
 391}
 392
 393pub fn merge_json_lenient_value_into(
 394    source: serde_json_lenient::Value,
 395    target: &mut serde_json_lenient::Value,
 396) {
 397    match (source, target) {
 398        (serde_json_lenient::Value::Object(source), serde_json_lenient::Value::Object(target)) => {
 399            for (key, value) in source {
 400                if let Some(target) = target.get_mut(&key) {
 401                    merge_json_lenient_value_into(value, target);
 402                } else {
 403                    target.insert(key, value);
 404                }
 405            }
 406        }
 407
 408        (serde_json_lenient::Value::Array(source), serde_json_lenient::Value::Array(target)) => {
 409            for value in source {
 410                target.push(value);
 411            }
 412        }
 413
 414        (source, target) => *target = source,
 415    }
 416}
 417
 418pub fn merge_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
 419    use serde_json::Value;
 420
 421    match (source, target) {
 422        (Value::Object(source), Value::Object(target)) => {
 423            for (key, value) in source {
 424                if let Some(target) = target.get_mut(&key) {
 425                    merge_json_value_into(value, target);
 426                } else {
 427                    target.insert(key, value);
 428                }
 429            }
 430        }
 431
 432        (Value::Array(source), Value::Array(target)) => {
 433            for value in source {
 434                target.push(value);
 435            }
 436        }
 437
 438        (source, target) => *target = source,
 439    }
 440}
 441
 442pub fn merge_non_null_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
 443    use serde_json::Value;
 444    if let Value::Object(source_object) = source {
 445        let target_object = if let Value::Object(target) = target {
 446            target
 447        } else {
 448            *target = Value::Object(Default::default());
 449            target.as_object_mut().unwrap()
 450        };
 451        for (key, value) in source_object {
 452            if let Some(target) = target_object.get_mut(&key) {
 453                merge_non_null_json_value_into(value, target);
 454            } else if !value.is_null() {
 455                target_object.insert(key, value);
 456            }
 457        }
 458    } else if !source.is_null() {
 459        *target = source
 460    }
 461}
 462
 463pub fn measure<R>(label: &str, f: impl FnOnce() -> R) -> R {
 464    static ZED_MEASUREMENTS: OnceLock<bool> = OnceLock::new();
 465    let zed_measurements = ZED_MEASUREMENTS.get_or_init(|| {
 466        env::var("ZED_MEASUREMENTS")
 467            .map(|measurements| measurements == "1" || measurements == "true")
 468            .unwrap_or(false)
 469    });
 470
 471    if *zed_measurements {
 472        let start = Instant::now();
 473        let result = f();
 474        let elapsed = start.elapsed();
 475        eprintln!("{}: {:?}", label, elapsed);
 476        result
 477    } else {
 478        f()
 479    }
 480}
 481
 482pub fn expanded_and_wrapped_usize_range(
 483    range: Range<usize>,
 484    additional_before: usize,
 485    additional_after: usize,
 486    wrap_length: usize,
 487) -> impl Iterator<Item = usize> {
 488    let start_wraps = range.start < additional_before;
 489    let end_wraps = wrap_length < range.end + additional_after;
 490    if start_wraps && end_wraps {
 491        Either::Left(0..wrap_length)
 492    } else if start_wraps {
 493        let wrapped_start = (range.start + wrap_length).saturating_sub(additional_before);
 494        if wrapped_start <= range.end {
 495            Either::Left(0..wrap_length)
 496        } else {
 497            Either::Right((0..range.end + additional_after).chain(wrapped_start..wrap_length))
 498        }
 499    } else if end_wraps {
 500        let wrapped_end = range.end + additional_after - wrap_length;
 501        if range.start <= wrapped_end {
 502            Either::Left(0..wrap_length)
 503        } else {
 504            Either::Right((0..wrapped_end).chain(range.start - additional_before..wrap_length))
 505        }
 506    } else {
 507        Either::Left((range.start - additional_before)..(range.end + additional_after))
 508    }
 509}
 510
 511/// Yields `[i, i + 1, i - 1, i + 2, ..]`, each modulo `wrap_length` and bounded by
 512/// `additional_before` and `additional_after`. If the wrapping causes overlap, duplicates are not
 513/// emitted. If wrap_length is 0, nothing is yielded.
 514pub fn wrapped_usize_outward_from(
 515    start: usize,
 516    additional_before: usize,
 517    additional_after: usize,
 518    wrap_length: usize,
 519) -> impl Iterator<Item = usize> {
 520    let mut count = 0;
 521    let mut after_offset = 1;
 522    let mut before_offset = 1;
 523
 524    std::iter::from_fn(move || {
 525        count += 1;
 526        if count > wrap_length {
 527            None
 528        } else if count == 1 {
 529            Some(start % wrap_length)
 530        } else if after_offset <= additional_after && after_offset <= before_offset {
 531            let value = (start + after_offset) % wrap_length;
 532            after_offset += 1;
 533            Some(value)
 534        } else if before_offset <= additional_before {
 535            let value = (start + wrap_length - before_offset) % wrap_length;
 536            before_offset += 1;
 537            Some(value)
 538        } else if after_offset <= additional_after {
 539            let value = (start + after_offset) % wrap_length;
 540            after_offset += 1;
 541            Some(value)
 542        } else {
 543            None
 544        }
 545    })
 546}
 547
 548pub trait ResultExt<E> {
 549    type Ok;
 550
 551    fn log_err(self) -> Option<Self::Ok>;
 552    /// Assert that this result should never be an error in development or tests.
 553    fn debug_assert_ok(self, reason: &str) -> Self;
 554    fn warn_on_err(self) -> Option<Self::Ok>;
 555    fn log_with_level(self, level: log::Level) -> Option<Self::Ok>;
 556    fn anyhow(self) -> anyhow::Result<Self::Ok>
 557    where
 558        E: Into<anyhow::Error>;
 559}
 560
 561impl<T, E> ResultExt<E> for Result<T, E>
 562where
 563    E: std::fmt::Debug,
 564{
 565    type Ok = T;
 566
 567    #[track_caller]
 568    fn log_err(self) -> Option<T> {
 569        self.log_with_level(log::Level::Error)
 570    }
 571
 572    #[track_caller]
 573    fn debug_assert_ok(self, reason: &str) -> Self {
 574        if let Err(error) = &self {
 575            debug_panic!("{reason} - {error:?}");
 576        }
 577        self
 578    }
 579
 580    #[track_caller]
 581    fn warn_on_err(self) -> Option<T> {
 582        self.log_with_level(log::Level::Warn)
 583    }
 584
 585    #[track_caller]
 586    fn log_with_level(self, level: log::Level) -> Option<T> {
 587        match self {
 588            Ok(value) => Some(value),
 589            Err(error) => {
 590                log_error_with_caller(*Location::caller(), error, level);
 591                None
 592            }
 593        }
 594    }
 595
 596    fn anyhow(self) -> anyhow::Result<T>
 597    where
 598        E: Into<anyhow::Error>,
 599    {
 600        self.map_err(Into::into)
 601    }
 602}
 603
 604fn log_error_with_caller<E>(caller: core::panic::Location<'_>, error: E, level: log::Level)
 605where
 606    E: std::fmt::Debug,
 607{
 608    #[cfg(not(target_os = "windows"))]
 609    let file = caller.file();
 610    #[cfg(target_os = "windows")]
 611    let file = caller.file().replace('\\', "/");
 612    // In this codebase all crates reside in a `crates` directory,
 613    // so discard the prefix up to that segment to find the crate name
 614    let target = file
 615        .split_once("crates/")
 616        .and_then(|(_, s)| s.split_once("/src/"));
 617
 618    let module_path = target.map(|(krate, module)| {
 619        krate.to_owned() + "::" + &module.trim_end_matches(".rs").replace('/', "::")
 620    });
 621    log::logger().log(
 622        &log::Record::builder()
 623            .target(target.map_or("", |(krate, _)| krate))
 624            .module_path(module_path.as_deref())
 625            .args(format_args!("{:?}", error))
 626            .file(Some(caller.file()))
 627            .line(Some(caller.line()))
 628            .level(level)
 629            .build(),
 630    );
 631}
 632
 633pub fn log_err<E: std::fmt::Debug>(error: &E) {
 634    log_error_with_caller(*Location::caller(), error, log::Level::Error);
 635}
 636
 637pub trait TryFutureExt {
 638    fn log_err(self) -> LogErrorFuture<Self>
 639    where
 640        Self: Sized;
 641
 642    fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
 643    where
 644        Self: Sized;
 645
 646    fn warn_on_err(self) -> LogErrorFuture<Self>
 647    where
 648        Self: Sized;
 649    fn unwrap(self) -> UnwrapFuture<Self>
 650    where
 651        Self: Sized;
 652}
 653
 654impl<F, T, E> TryFutureExt for F
 655where
 656    F: Future<Output = Result<T, E>>,
 657    E: std::fmt::Debug,
 658{
 659    #[track_caller]
 660    fn log_err(self) -> LogErrorFuture<Self>
 661    where
 662        Self: Sized,
 663    {
 664        let location = Location::caller();
 665        LogErrorFuture(self, log::Level::Error, *location)
 666    }
 667
 668    fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
 669    where
 670        Self: Sized,
 671    {
 672        LogErrorFuture(self, log::Level::Error, location)
 673    }
 674
 675    #[track_caller]
 676    fn warn_on_err(self) -> LogErrorFuture<Self>
 677    where
 678        Self: Sized,
 679    {
 680        let location = Location::caller();
 681        LogErrorFuture(self, log::Level::Warn, *location)
 682    }
 683
 684    fn unwrap(self) -> UnwrapFuture<Self>
 685    where
 686        Self: Sized,
 687    {
 688        UnwrapFuture(self)
 689    }
 690}
 691
 692#[must_use]
 693pub struct LogErrorFuture<F>(F, log::Level, core::panic::Location<'static>);
 694
 695impl<F, T, E> Future for LogErrorFuture<F>
 696where
 697    F: Future<Output = Result<T, E>>,
 698    E: std::fmt::Debug,
 699{
 700    type Output = Option<T>;
 701
 702    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
 703        let level = self.1;
 704        let location = self.2;
 705        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
 706        match inner.poll(cx) {
 707            Poll::Ready(output) => Poll::Ready(match output {
 708                Ok(output) => Some(output),
 709                Err(error) => {
 710                    log_error_with_caller(location, error, level);
 711                    None
 712                }
 713            }),
 714            Poll::Pending => Poll::Pending,
 715        }
 716    }
 717}
 718
 719pub struct UnwrapFuture<F>(F);
 720
 721impl<F, T, E> Future for UnwrapFuture<F>
 722where
 723    F: Future<Output = Result<T, E>>,
 724    E: std::fmt::Debug,
 725{
 726    type Output = T;
 727
 728    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
 729        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
 730        match inner.poll(cx) {
 731            Poll::Ready(result) => Poll::Ready(result.unwrap()),
 732            Poll::Pending => Poll::Pending,
 733        }
 734    }
 735}
 736
 737pub struct Deferred<F: FnOnce()>(Option<F>);
 738
 739impl<F: FnOnce()> Deferred<F> {
 740    /// Drop without running the deferred function.
 741    pub fn abort(mut self) {
 742        self.0.take();
 743    }
 744}
 745
 746impl<F: FnOnce()> Drop for Deferred<F> {
 747    fn drop(&mut self) {
 748        if let Some(f) = self.0.take() {
 749            f()
 750        }
 751    }
 752}
 753
 754/// Run the given function when the returned value is dropped (unless it's cancelled).
 755#[must_use]
 756pub fn defer<F: FnOnce()>(f: F) -> Deferred<F> {
 757    Deferred(Some(f))
 758}
 759
 760#[cfg(any(test, feature = "test-support"))]
 761mod rng {
 762    use rand::prelude::*;
 763
 764    pub struct RandomCharIter<T: Rng> {
 765        rng: T,
 766        simple_text: bool,
 767    }
 768
 769    impl<T: Rng> RandomCharIter<T> {
 770        pub fn new(rng: T) -> Self {
 771            Self {
 772                rng,
 773                simple_text: std::env::var("SIMPLE_TEXT").is_ok_and(|v| !v.is_empty()),
 774            }
 775        }
 776
 777        pub fn with_simple_text(mut self) -> Self {
 778            self.simple_text = true;
 779            self
 780        }
 781    }
 782
 783    impl<T: Rng> Iterator for RandomCharIter<T> {
 784        type Item = char;
 785
 786        fn next(&mut self) -> Option<Self::Item> {
 787            if self.simple_text {
 788                return if self.rng.random_range(0..100) < 5 {
 789                    Some('\n')
 790                } else {
 791                    Some(self.rng.random_range(b'a'..b'z' + 1).into())
 792                };
 793            }
 794
 795            match self.rng.random_range(0..100) {
 796                // whitespace
 797                0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.rng).copied(),
 798                // two-byte greek letters
 799                20..=32 => char::from_u32(self.rng.random_range(('Ξ±' as u32)..('Ο' as u32 + 1))),
 800                // // three-byte characters
 801                33..=45 => ['β', 'β
', 'β', 'β', 'β']
 802                    .choose(&mut self.rng)
 803                    .copied(),
 804                // // four-byte characters
 805                46..=58 => ['π', 'π', 'π', 'π'].choose(&mut self.rng).copied(),
 806                // ascii letters
 807                _ => Some(self.rng.random_range(b'a'..b'z' + 1).into()),
 808            }
 809        }
 810    }
 811}
 812#[cfg(any(test, feature = "test-support"))]
 813pub use rng::RandomCharIter;
 814
 815/// Get an embedded file as a string.
 816pub fn asset_str<A: rust_embed::RustEmbed>(path: &str) -> Cow<'static, str> {
 817    match A::get(path).expect(path).data {
 818        Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()),
 819        Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()),
 820    }
 821}
 822
 823/// Expands to an immediately-invoked function expression. Good for using the ? operator
 824/// in functions which do not return an Option or Result.
 825///
 826/// Accepts a normal block, an async block, or an async move block.
 827#[macro_export]
 828macro_rules! maybe {
 829    ($block:block) => {
 830        (|| $block)()
 831    };
 832    (async $block:block) => {
 833        (async || $block)()
 834    };
 835    (async move $block:block) => {
 836        (async move || $block)()
 837    };
 838}
 839
 840pub trait RangeExt<T> {
 841    fn sorted(&self) -> Self;
 842    fn to_inclusive(&self) -> RangeInclusive<T>;
 843    fn overlaps(&self, other: &Range<T>) -> bool;
 844    fn contains_inclusive(&self, other: &Range<T>) -> bool;
 845}
 846
 847impl<T: Ord + Clone> RangeExt<T> for Range<T> {
 848    fn sorted(&self) -> Self {
 849        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
 850    }
 851
 852    fn to_inclusive(&self) -> RangeInclusive<T> {
 853        self.start.clone()..=self.end.clone()
 854    }
 855
 856    fn overlaps(&self, other: &Range<T>) -> bool {
 857        self.start < other.end && other.start < self.end
 858    }
 859
 860    fn contains_inclusive(&self, other: &Range<T>) -> bool {
 861        self.start <= other.start && other.end <= self.end
 862    }
 863}
 864
 865impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
 866    fn sorted(&self) -> Self {
 867        cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
 868    }
 869
 870    fn to_inclusive(&self) -> RangeInclusive<T> {
 871        self.clone()
 872    }
 873
 874    fn overlaps(&self, other: &Range<T>) -> bool {
 875        self.start() < &other.end && &other.start <= self.end()
 876    }
 877
 878    fn contains_inclusive(&self, other: &Range<T>) -> bool {
 879        self.start() <= &other.start && &other.end <= self.end()
 880    }
 881}
 882
 883/// A way to sort strings with starting numbers numerically first, falling back to alphanumeric one,
 884/// case-insensitive.
 885///
 886/// This is useful for turning regular alphanumerically sorted sequences as `1-abc, 10, 11-def, .., 2, 21-abc`
 887/// into `1-abc, 2, 10, 11-def, .., 21-abc`
 888#[derive(Debug, PartialEq, Eq)]
 889pub struct NumericPrefixWithSuffix<'a>(Option<u64>, &'a str);
 890
 891impl<'a> NumericPrefixWithSuffix<'a> {
 892    pub fn from_numeric_prefixed_str(str: &'a str) -> Self {
 893        let i = str.chars().take_while(|c| c.is_ascii_digit()).count();
 894        let (prefix, remainder) = str.split_at(i);
 895
 896        let prefix = prefix.parse().ok();
 897        Self(prefix, remainder)
 898    }
 899}
 900
 901/// When dealing with equality, we need to consider the case of the strings to achieve strict equality
 902/// to handle cases like "a" < "A" instead of "a" == "A".
 903impl Ord for NumericPrefixWithSuffix<'_> {
 904    fn cmp(&self, other: &Self) -> Ordering {
 905        match (self.0, other.0) {
 906            (None, None) => UniCase::new(self.1)
 907                .cmp(&UniCase::new(other.1))
 908                .then_with(|| self.1.cmp(other.1).reverse()),
 909            (None, Some(_)) => Ordering::Greater,
 910            (Some(_), None) => Ordering::Less,
 911            (Some(a), Some(b)) => a.cmp(&b).then_with(|| {
 912                UniCase::new(self.1)
 913                    .cmp(&UniCase::new(other.1))
 914                    .then_with(|| self.1.cmp(other.1).reverse())
 915            }),
 916        }
 917    }
 918}
 919
 920impl PartialOrd for NumericPrefixWithSuffix<'_> {
 921    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
 922        Some(self.cmp(other))
 923    }
 924}
 925
 926/// Capitalizes the first character of a string.
 927///
 928/// This function takes a string slice as input and returns a new `String` with the first character
 929/// capitalized.
 930///
 931/// # Examples
 932///
 933/// ```
 934/// use util::capitalize;
 935///
 936/// assert_eq!(capitalize("hello"), "Hello");
 937/// assert_eq!(capitalize("WORLD"), "WORLD");
 938/// assert_eq!(capitalize(""), "");
 939/// ```
 940pub fn capitalize(str: &str) -> String {
 941    let mut chars = str.chars();
 942    match chars.next() {
 943        None => String::new(),
 944        Some(first_char) => first_char.to_uppercase().collect::<String>() + chars.as_str(),
 945    }
 946}
 947
 948fn emoji_regex() -> &'static Regex {
 949    static EMOJI_REGEX: LazyLock<Regex> =
 950        LazyLock::new(|| Regex::new("(\\p{Emoji}|\u{200D})").unwrap());
 951    &EMOJI_REGEX
 952}
 953
 954/// Returns true if the given string consists of emojis only.
 955/// E.g. "π¨βπ©βπ§βπ§π" will return true, but "π!" will return false.
 956pub fn word_consists_of_emojis(s: &str) -> bool {
 957    let mut prev_end = 0;
 958    for capture in emoji_regex().find_iter(s) {
 959        if capture.start() != prev_end {
 960            return false;
 961        }
 962        prev_end = capture.end();
 963    }
 964    prev_end == s.len()
 965}
 966
 967/// Similar to `str::split`, but also provides byte-offset ranges of the results. Unlike
 968/// `str::split`, this is not generic on pattern types and does not return an `Iterator`.
 969pub fn split_str_with_ranges(s: &str, pat: impl Fn(char) -> bool) -> Vec<(Range<usize>, &str)> {
 970    let mut result = Vec::new();
 971    let mut start = 0;
 972
 973    for (i, ch) in s.char_indices() {
 974        if pat(ch) {
 975            if i > start {
 976                result.push((start..i, &s[start..i]));
 977            }
 978            start = i + ch.len_utf8();
 979        }
 980    }
 981
 982    if s.len() > start {
 983        result.push((start..s.len(), &s[start..s.len()]));
 984    }
 985
 986    result
 987}
 988
 989pub fn default<D: Default>() -> D {
 990    Default::default()
 991}
 992
 993pub use self::shell::{
 994    get_default_system_shell, get_default_system_shell_preferring_bash, get_system_shell,
 995};
 996
 997#[derive(Debug)]
 998pub enum ConnectionResult<O> {
 999    Timeout,
1000    ConnectionReset,
1001    Result(anyhow::Result<O>),
1002}
1003
1004impl<O> ConnectionResult<O> {
1005    pub fn into_response(self) -> anyhow::Result<O> {
1006        match self {
1007            ConnectionResult::Timeout => anyhow::bail!("Request timed out"),
1008            ConnectionResult::ConnectionReset => anyhow::bail!("Server reset the connection"),
1009            ConnectionResult::Result(r) => r,
1010        }
1011    }
1012}
1013
1014impl<O> From<anyhow::Result<O>> for ConnectionResult<O> {
1015    fn from(result: anyhow::Result<O>) -> Self {
1016        ConnectionResult::Result(result)
1017    }
1018}
1019
1020#[track_caller]
1021pub fn some_or_debug_panic<T>(option: Option<T>) -> Option<T> {
1022    #[cfg(debug_assertions)]
1023    if option.is_none() {
1024        panic!("Unexpected None");
1025    }
1026    option
1027}
1028
1029#[cfg(test)]
1030mod tests {
1031    use super::*;
1032
1033    #[test]
1034    fn test_extend_sorted() {
1035        let mut vec = vec![];
1036
1037        extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
1038        assert_eq!(vec, &[21, 17, 13, 8, 1]);
1039
1040        extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
1041        assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
1042
1043        extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
1044        assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
1045    }
1046
1047    #[test]
1048    fn test_truncate_to_bottom_n_sorted_by() {
1049        let mut vec: Vec<u32> = vec![5, 2, 3, 4, 1];
1050        truncate_to_bottom_n_sorted_by(&mut vec, 10, &u32::cmp);
1051        assert_eq!(vec, &[1, 2, 3, 4, 5]);
1052
1053        vec = vec![5, 2, 3, 4, 1];
1054        truncate_to_bottom_n_sorted_by(&mut vec, 5, &u32::cmp);
1055        assert_eq!(vec, &[1, 2, 3, 4, 5]);
1056
1057        vec = vec![5, 2, 3, 4, 1];
1058        truncate_to_bottom_n_sorted_by(&mut vec, 4, &u32::cmp);
1059        assert_eq!(vec, &[1, 2, 3, 4]);
1060
1061        vec = vec![5, 2, 3, 4, 1];
1062        truncate_to_bottom_n_sorted_by(&mut vec, 1, &u32::cmp);
1063        assert_eq!(vec, &[1]);
1064
1065        vec = vec![5, 2, 3, 4, 1];
1066        truncate_to_bottom_n_sorted_by(&mut vec, 0, &u32::cmp);
1067        assert!(vec.is_empty());
1068    }
1069
1070    #[test]
1071    fn test_iife() {
1072        fn option_returning_function() -> Option<()> {
1073            None
1074        }
1075
1076        let foo = maybe!({
1077            option_returning_function()?;
1078            Some(())
1079        });
1080
1081        assert_eq!(foo, None);
1082    }
1083
1084    #[test]
1085    fn test_truncate_and_trailoff() {
1086        assert_eq!(truncate_and_trailoff("", 5), "");
1087        assert_eq!(truncate_and_trailoff("aaaaaa", 7), "aaaaaa");
1088        assert_eq!(truncate_and_trailoff("aaaaaa", 6), "aaaaaa");
1089        assert_eq!(truncate_and_trailoff("aaaaaa", 5), "aaaaaβ¦");
1090        assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
1091        assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
1092        assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèèβ¦");
1093    }
1094
1095    #[test]
1096    fn test_truncate_and_remove_front() {
1097        assert_eq!(truncate_and_remove_front("", 5), "");
1098        assert_eq!(truncate_and_remove_front("aaaaaa", 7), "aaaaaa");
1099        assert_eq!(truncate_and_remove_front("aaaaaa", 6), "aaaaaa");
1100        assert_eq!(truncate_and_remove_front("aaaaaa", 5), "β¦aaaaa");
1101        assert_eq!(truncate_and_remove_front("èèèèèè", 7), "èèèèèè");
1102        assert_eq!(truncate_and_remove_front("èèèèèè", 6), "èèèèèè");
1103        assert_eq!(truncate_and_remove_front("èèèèèè", 5), "β¦Γ¨Γ¨Γ¨Γ¨Γ¨");
1104    }
1105
1106    #[test]
1107    fn test_numeric_prefix_str_method() {
1108        let target = "1a";
1109        assert_eq!(
1110            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1111            NumericPrefixWithSuffix(Some(1), "a")
1112        );
1113
1114        let target = "12ab";
1115        assert_eq!(
1116            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1117            NumericPrefixWithSuffix(Some(12), "ab")
1118        );
1119
1120        let target = "12_ab";
1121        assert_eq!(
1122            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1123            NumericPrefixWithSuffix(Some(12), "_ab")
1124        );
1125
1126        let target = "1_2ab";
1127        assert_eq!(
1128            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1129            NumericPrefixWithSuffix(Some(1), "_2ab")
1130        );
1131
1132        let target = "1.2";
1133        assert_eq!(
1134            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1135            NumericPrefixWithSuffix(Some(1), ".2")
1136        );
1137
1138        let target = "1.2_a";
1139        assert_eq!(
1140            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1141            NumericPrefixWithSuffix(Some(1), ".2_a")
1142        );
1143
1144        let target = "12.2_a";
1145        assert_eq!(
1146            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1147            NumericPrefixWithSuffix(Some(12), ".2_a")
1148        );
1149
1150        let target = "12a.2_a";
1151        assert_eq!(
1152            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1153            NumericPrefixWithSuffix(Some(12), "a.2_a")
1154        );
1155    }
1156
1157    #[test]
1158    fn test_numeric_prefix_with_suffix() {
1159        let mut sorted = vec!["1-abc", "10", "11def", "2", "21-abc"];
1160        sorted.sort_by_key(|s| NumericPrefixWithSuffix::from_numeric_prefixed_str(s));
1161        assert_eq!(sorted, ["1-abc", "2", "10", "11def", "21-abc"]);
1162
1163        for numeric_prefix_less in ["numeric_prefix_less", "aaa", "~β’Β£"] {
1164            assert_eq!(
1165                NumericPrefixWithSuffix::from_numeric_prefixed_str(numeric_prefix_less),
1166                NumericPrefixWithSuffix(None, numeric_prefix_less),
1167                "String without numeric prefix `{numeric_prefix_less}` should not be converted into NumericPrefixWithSuffix"
1168            )
1169        }
1170    }
1171
1172    #[test]
1173    fn test_word_consists_of_emojis() {
1174        let words_to_test = vec![
1175            ("π¨βπ©βπ§βπ§ππ₯", true),
1176            ("π", true),
1177            ("!π", false),
1178            ("π!", false),
1179            ("π ", false),
1180            (" π", false),
1181            ("Test", false),
1182        ];
1183
1184        for (text, expected_result) in words_to_test {
1185            assert_eq!(word_consists_of_emojis(text), expected_result);
1186        }
1187    }
1188
1189    #[test]
1190    fn test_truncate_lines_and_trailoff() {
1191        let text = r#"Line 1
1192Line 2
1193Line 3"#;
1194
1195        assert_eq!(
1196            truncate_lines_and_trailoff(text, 2),
1197            r#"Line 1
1198β¦"#
1199        );
1200
1201        assert_eq!(
1202            truncate_lines_and_trailoff(text, 3),
1203            r#"Line 1
1204Line 2
1205β¦"#
1206        );
1207
1208        assert_eq!(
1209            truncate_lines_and_trailoff(text, 4),
1210            r#"Line 1
1211Line 2
1212Line 3"#
1213        );
1214    }
1215
1216    #[test]
1217    fn test_expanded_and_wrapped_usize_range() {
1218        // Neither wrap
1219        assert_eq!(
1220            expanded_and_wrapped_usize_range(2..4, 1, 1, 8).collect::<Vec<usize>>(),
1221            (1..5).collect::<Vec<usize>>()
1222        );
1223        // Start wraps
1224        assert_eq!(
1225            expanded_and_wrapped_usize_range(2..4, 3, 1, 8).collect::<Vec<usize>>(),
1226            ((0..5).chain(7..8)).collect::<Vec<usize>>()
1227        );
1228        // Start wraps all the way around
1229        assert_eq!(
1230            expanded_and_wrapped_usize_range(2..4, 5, 1, 8).collect::<Vec<usize>>(),
1231            (0..8).collect::<Vec<usize>>()
1232        );
1233        // Start wraps all the way around and past 0
1234        assert_eq!(
1235            expanded_and_wrapped_usize_range(2..4, 10, 1, 8).collect::<Vec<usize>>(),
1236            (0..8).collect::<Vec<usize>>()
1237        );
1238        // End wraps
1239        assert_eq!(
1240            expanded_and_wrapped_usize_range(3..5, 1, 4, 8).collect::<Vec<usize>>(),
1241            (0..1).chain(2..8).collect::<Vec<usize>>()
1242        );
1243        // End wraps all the way around
1244        assert_eq!(
1245            expanded_and_wrapped_usize_range(3..5, 1, 5, 8).collect::<Vec<usize>>(),
1246            (0..8).collect::<Vec<usize>>()
1247        );
1248        // End wraps all the way around and past the end
1249        assert_eq!(
1250            expanded_and_wrapped_usize_range(3..5, 1, 10, 8).collect::<Vec<usize>>(),
1251            (0..8).collect::<Vec<usize>>()
1252        );
1253        // Both start and end wrap
1254        assert_eq!(
1255            expanded_and_wrapped_usize_range(3..5, 4, 4, 8).collect::<Vec<usize>>(),
1256            (0..8).collect::<Vec<usize>>()
1257        );
1258    }
1259
1260    #[test]
1261    fn test_wrapped_usize_outward_from() {
1262        // No wrapping
1263        assert_eq!(
1264            wrapped_usize_outward_from(4, 2, 2, 10).collect::<Vec<usize>>(),
1265            vec![4, 5, 3, 6, 2]
1266        );
1267        // Wrapping at end
1268        assert_eq!(
1269            wrapped_usize_outward_from(8, 2, 3, 10).collect::<Vec<usize>>(),
1270            vec![8, 9, 7, 0, 6, 1]
1271        );
1272        // Wrapping at start
1273        assert_eq!(
1274            wrapped_usize_outward_from(1, 3, 2, 10).collect::<Vec<usize>>(),
1275            vec![1, 2, 0, 3, 9, 8]
1276        );
1277        // All values wrap around
1278        assert_eq!(
1279            wrapped_usize_outward_from(5, 10, 10, 8).collect::<Vec<usize>>(),
1280            vec![5, 6, 4, 7, 3, 0, 2, 1]
1281        );
1282        // None before / after
1283        assert_eq!(
1284            wrapped_usize_outward_from(3, 0, 0, 8).collect::<Vec<usize>>(),
1285            vec![3]
1286        );
1287        // Starting point already wrapped
1288        assert_eq!(
1289            wrapped_usize_outward_from(15, 2, 2, 10).collect::<Vec<usize>>(),
1290            vec![5, 6, 4, 7, 3]
1291        );
1292        // wrap_length of 0
1293        assert_eq!(
1294            wrapped_usize_outward_from(4, 2, 2, 0).collect::<Vec<usize>>(),
1295            Vec::<usize>::new()
1296        );
1297    }
1298
1299    #[test]
1300    fn test_split_with_ranges() {
1301        let input = "hi";
1302        let result = split_str_with_ranges(input, |c| c == ' ');
1303
1304        assert_eq!(result.len(), 1);
1305        assert_eq!(result[0], (0..2, "hi"));
1306
1307        let input = "hΓ©lloπ¦world";
1308        let result = split_str_with_ranges(input, |c| c == 'π¦');
1309
1310        assert_eq!(result.len(), 2);
1311        assert_eq!(result[0], (0..6, "hΓ©llo")); // 'Γ©' is 2 bytes
1312        assert_eq!(result[1], (10..15, "world")); // 'π¦' is 4 bytes
1313    }
1314}