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