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