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('/'))
609 .map(|(p, _)| p);
610
611 log::logger().log(
612 &log::Record::builder()
613 .target(target.unwrap_or(""))
614 .module_path(target)
615 .args(format_args!("{:?}", error))
616 .file(Some(caller.file()))
617 .line(Some(caller.line()))
618 .level(level)
619 .build(),
620 );
621}
622
623pub fn log_err<E: std::fmt::Debug>(error: &E) {
624 log_error_with_caller(*Location::caller(), error, log::Level::Warn);
625}
626
627pub trait TryFutureExt {
628 fn log_err(self) -> LogErrorFuture<Self>
629 where
630 Self: Sized;
631
632 fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
633 where
634 Self: Sized;
635
636 fn warn_on_err(self) -> LogErrorFuture<Self>
637 where
638 Self: Sized;
639 fn unwrap(self) -> UnwrapFuture<Self>
640 where
641 Self: Sized;
642}
643
644impl<F, T, E> TryFutureExt for F
645where
646 F: Future<Output = Result<T, E>>,
647 E: std::fmt::Debug,
648{
649 #[track_caller]
650 fn log_err(self) -> LogErrorFuture<Self>
651 where
652 Self: Sized,
653 {
654 let location = Location::caller();
655 LogErrorFuture(self, log::Level::Error, *location)
656 }
657
658 fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
659 where
660 Self: Sized,
661 {
662 LogErrorFuture(self, log::Level::Error, location)
663 }
664
665 #[track_caller]
666 fn warn_on_err(self) -> LogErrorFuture<Self>
667 where
668 Self: Sized,
669 {
670 let location = Location::caller();
671 LogErrorFuture(self, log::Level::Warn, *location)
672 }
673
674 fn unwrap(self) -> UnwrapFuture<Self>
675 where
676 Self: Sized,
677 {
678 UnwrapFuture(self)
679 }
680}
681
682#[must_use]
683pub struct LogErrorFuture<F>(F, log::Level, core::panic::Location<'static>);
684
685impl<F, T, E> Future for LogErrorFuture<F>
686where
687 F: Future<Output = Result<T, E>>,
688 E: std::fmt::Debug,
689{
690 type Output = Option<T>;
691
692 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
693 let level = self.1;
694 let location = self.2;
695 let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
696 match inner.poll(cx) {
697 Poll::Ready(output) => Poll::Ready(match output {
698 Ok(output) => Some(output),
699 Err(error) => {
700 log_error_with_caller(location, error, level);
701 None
702 }
703 }),
704 Poll::Pending => Poll::Pending,
705 }
706 }
707}
708
709pub struct UnwrapFuture<F>(F);
710
711impl<F, T, E> Future for UnwrapFuture<F>
712where
713 F: Future<Output = Result<T, E>>,
714 E: std::fmt::Debug,
715{
716 type Output = T;
717
718 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
719 let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
720 match inner.poll(cx) {
721 Poll::Ready(result) => Poll::Ready(result.unwrap()),
722 Poll::Pending => Poll::Pending,
723 }
724 }
725}
726
727pub struct Deferred<F: FnOnce()>(Option<F>);
728
729impl<F: FnOnce()> Deferred<F> {
730 /// Drop without running the deferred function.
731 pub fn abort(mut self) {
732 self.0.take();
733 }
734}
735
736impl<F: FnOnce()> Drop for Deferred<F> {
737 fn drop(&mut self) {
738 if let Some(f) = self.0.take() {
739 f()
740 }
741 }
742}
743
744/// Run the given function when the returned value is dropped (unless it's cancelled).
745#[must_use]
746pub fn defer<F: FnOnce()>(f: F) -> Deferred<F> {
747 Deferred(Some(f))
748}
749
750#[cfg(any(test, feature = "test-support"))]
751mod rng {
752 use rand::prelude::*;
753
754 pub struct RandomCharIter<T: Rng> {
755 rng: T,
756 simple_text: bool,
757 }
758
759 impl<T: Rng> RandomCharIter<T> {
760 pub fn new(rng: T) -> Self {
761 Self {
762 rng,
763 simple_text: std::env::var("SIMPLE_TEXT").is_ok_and(|v| !v.is_empty()),
764 }
765 }
766
767 pub fn with_simple_text(mut self) -> Self {
768 self.simple_text = true;
769 self
770 }
771 }
772
773 impl<T: Rng> Iterator for RandomCharIter<T> {
774 type Item = char;
775
776 fn next(&mut self) -> Option<Self::Item> {
777 if self.simple_text {
778 return if self.rng.random_range(0..100) < 5 {
779 Some('\n')
780 } else {
781 Some(self.rng.random_range(b'a'..b'z' + 1).into())
782 };
783 }
784
785 match self.rng.random_range(0..100) {
786 // whitespace
787 0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.rng).copied(),
788 // two-byte greek letters
789 20..=32 => char::from_u32(self.rng.random_range(('Ξ±' as u32)..('Ο' as u32 + 1))),
790 // // three-byte characters
791 33..=45 => ['β', 'β
', 'β', 'β', 'β']
792 .choose(&mut self.rng)
793 .copied(),
794 // // four-byte characters
795 46..=58 => ['π', 'π', 'π', 'π'].choose(&mut self.rng).copied(),
796 // ascii letters
797 _ => Some(self.rng.random_range(b'a'..b'z' + 1).into()),
798 }
799 }
800 }
801}
802#[cfg(any(test, feature = "test-support"))]
803pub use rng::RandomCharIter;
804
805/// Get an embedded file as a string.
806pub fn asset_str<A: rust_embed::RustEmbed>(path: &str) -> Cow<'static, str> {
807 match A::get(path).expect(path).data {
808 Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()),
809 Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()),
810 }
811}
812
813/// Expands to an immediately-invoked function expression. Good for using the ? operator
814/// in functions which do not return an Option or Result.
815///
816/// Accepts a normal block, an async block, or an async move block.
817#[macro_export]
818macro_rules! maybe {
819 ($block:block) => {
820 (|| $block)()
821 };
822 (async $block:block) => {
823 (async || $block)()
824 };
825 (async move $block:block) => {
826 (async move || $block)()
827 };
828}
829
830pub trait RangeExt<T> {
831 fn sorted(&self) -> Self;
832 fn to_inclusive(&self) -> RangeInclusive<T>;
833 fn overlaps(&self, other: &Range<T>) -> bool;
834 fn contains_inclusive(&self, other: &Range<T>) -> bool;
835}
836
837impl<T: Ord + Clone> RangeExt<T> for Range<T> {
838 fn sorted(&self) -> Self {
839 cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
840 }
841
842 fn to_inclusive(&self) -> RangeInclusive<T> {
843 self.start.clone()..=self.end.clone()
844 }
845
846 fn overlaps(&self, other: &Range<T>) -> bool {
847 self.start < other.end && other.start < self.end
848 }
849
850 fn contains_inclusive(&self, other: &Range<T>) -> bool {
851 self.start <= other.start && other.end <= self.end
852 }
853}
854
855impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
856 fn sorted(&self) -> Self {
857 cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
858 }
859
860 fn to_inclusive(&self) -> RangeInclusive<T> {
861 self.clone()
862 }
863
864 fn overlaps(&self, other: &Range<T>) -> bool {
865 self.start() < &other.end && &other.start <= self.end()
866 }
867
868 fn contains_inclusive(&self, other: &Range<T>) -> bool {
869 self.start() <= &other.start && &other.end <= self.end()
870 }
871}
872
873/// A way to sort strings with starting numbers numerically first, falling back to alphanumeric one,
874/// case-insensitive.
875///
876/// This is useful for turning regular alphanumerically sorted sequences as `1-abc, 10, 11-def, .., 2, 21-abc`
877/// into `1-abc, 2, 10, 11-def, .., 21-abc`
878#[derive(Debug, PartialEq, Eq)]
879pub struct NumericPrefixWithSuffix<'a>(Option<u64>, &'a str);
880
881impl<'a> NumericPrefixWithSuffix<'a> {
882 pub fn from_numeric_prefixed_str(str: &'a str) -> Self {
883 let i = str.chars().take_while(|c| c.is_ascii_digit()).count();
884 let (prefix, remainder) = str.split_at(i);
885
886 let prefix = prefix.parse().ok();
887 Self(prefix, remainder)
888 }
889}
890
891/// When dealing with equality, we need to consider the case of the strings to achieve strict equality
892/// to handle cases like "a" < "A" instead of "a" == "A".
893impl Ord for NumericPrefixWithSuffix<'_> {
894 fn cmp(&self, other: &Self) -> Ordering {
895 match (self.0, other.0) {
896 (None, None) => UniCase::new(self.1)
897 .cmp(&UniCase::new(other.1))
898 .then_with(|| self.1.cmp(other.1).reverse()),
899 (None, Some(_)) => Ordering::Greater,
900 (Some(_), None) => Ordering::Less,
901 (Some(a), Some(b)) => a.cmp(&b).then_with(|| {
902 UniCase::new(self.1)
903 .cmp(&UniCase::new(other.1))
904 .then_with(|| self.1.cmp(other.1).reverse())
905 }),
906 }
907 }
908}
909
910impl PartialOrd for NumericPrefixWithSuffix<'_> {
911 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
912 Some(self.cmp(other))
913 }
914}
915
916/// Capitalizes the first character of a string.
917///
918/// This function takes a string slice as input and returns a new `String` with the first character
919/// capitalized.
920///
921/// # Examples
922///
923/// ```
924/// use zed_util::capitalize;
925///
926/// assert_eq!(capitalize("hello"), "Hello");
927/// assert_eq!(capitalize("WORLD"), "WORLD");
928/// assert_eq!(capitalize(""), "");
929/// ```
930pub fn capitalize(str: &str) -> String {
931 let mut chars = str.chars();
932 match chars.next() {
933 None => String::new(),
934 Some(first_char) => first_char.to_uppercase().collect::<String>() + chars.as_str(),
935 }
936}
937
938fn emoji_regex() -> &'static Regex {
939 static EMOJI_REGEX: LazyLock<Regex> =
940 LazyLock::new(|| Regex::new("(\\p{Emoji}|\u{200D})").unwrap());
941 &EMOJI_REGEX
942}
943
944/// Returns true if the given string consists of emojis only.
945/// E.g. "π¨βπ©βπ§βπ§π" will return true, but "π!" will return false.
946pub fn word_consists_of_emojis(s: &str) -> bool {
947 let mut prev_end = 0;
948 for capture in emoji_regex().find_iter(s) {
949 if capture.start() != prev_end {
950 return false;
951 }
952 prev_end = capture.end();
953 }
954 prev_end == s.len()
955}
956
957/// Similar to `str::split`, but also provides byte-offset ranges of the results. Unlike
958/// `str::split`, this is not generic on pattern types and does not return an `Iterator`.
959pub fn split_str_with_ranges(s: &str, pat: impl Fn(char) -> bool) -> Vec<(Range<usize>, &str)> {
960 let mut result = Vec::new();
961 let mut start = 0;
962
963 for (i, ch) in s.char_indices() {
964 if pat(ch) {
965 if i > start {
966 result.push((start..i, &s[start..i]));
967 }
968 start = i + ch.len_utf8();
969 }
970 }
971
972 if s.len() > start {
973 result.push((start..s.len(), &s[start..s.len()]));
974 }
975
976 result
977}
978
979pub fn default<D: Default>() -> D {
980 Default::default()
981}
982
983pub use self::shell::{
984 get_default_system_shell, get_default_system_shell_preferring_bash, get_system_shell,
985};
986
987#[derive(Debug)]
988pub enum ConnectionResult<O> {
989 Timeout,
990 ConnectionReset,
991 Result(anyhow::Result<O>),
992}
993
994impl<O> ConnectionResult<O> {
995 pub fn into_response(self) -> anyhow::Result<O> {
996 match self {
997 ConnectionResult::Timeout => anyhow::bail!("Request timed out"),
998 ConnectionResult::ConnectionReset => anyhow::bail!("Server reset the connection"),
999 ConnectionResult::Result(r) => r,
1000 }
1001 }
1002}
1003
1004impl<O> From<anyhow::Result<O>> for ConnectionResult<O> {
1005 fn from(result: anyhow::Result<O>) -> Self {
1006 ConnectionResult::Result(result)
1007 }
1008}
1009
1010#[track_caller]
1011pub fn some_or_debug_panic<T>(option: Option<T>) -> Option<T> {
1012 #[cfg(debug_assertions)]
1013 if option.is_none() {
1014 panic!("Unexpected None");
1015 }
1016 option
1017}
1018
1019#[cfg(test)]
1020mod tests {
1021 use super::*;
1022
1023 #[test]
1024 fn test_extend_sorted() {
1025 let mut vec = vec![];
1026
1027 extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
1028 assert_eq!(vec, &[21, 17, 13, 8, 1]);
1029
1030 extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
1031 assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
1032
1033 extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
1034 assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
1035 }
1036
1037 #[test]
1038 fn test_truncate_to_bottom_n_sorted_by() {
1039 let mut vec: Vec<u32> = vec![5, 2, 3, 4, 1];
1040 truncate_to_bottom_n_sorted_by(&mut vec, 10, &u32::cmp);
1041 assert_eq!(vec, &[1, 2, 3, 4, 5]);
1042
1043 vec = vec![5, 2, 3, 4, 1];
1044 truncate_to_bottom_n_sorted_by(&mut vec, 5, &u32::cmp);
1045 assert_eq!(vec, &[1, 2, 3, 4, 5]);
1046
1047 vec = vec![5, 2, 3, 4, 1];
1048 truncate_to_bottom_n_sorted_by(&mut vec, 4, &u32::cmp);
1049 assert_eq!(vec, &[1, 2, 3, 4]);
1050
1051 vec = vec![5, 2, 3, 4, 1];
1052 truncate_to_bottom_n_sorted_by(&mut vec, 1, &u32::cmp);
1053 assert_eq!(vec, &[1]);
1054
1055 vec = vec![5, 2, 3, 4, 1];
1056 truncate_to_bottom_n_sorted_by(&mut vec, 0, &u32::cmp);
1057 assert!(vec.is_empty());
1058 }
1059
1060 #[test]
1061 fn test_iife() {
1062 fn option_returning_function() -> Option<()> {
1063 None
1064 }
1065
1066 let foo = maybe!({
1067 option_returning_function()?;
1068 Some(())
1069 });
1070
1071 assert_eq!(foo, None);
1072 }
1073
1074 #[test]
1075 fn test_truncate_and_trailoff() {
1076 assert_eq!(truncate_and_trailoff("", 5), "");
1077 assert_eq!(truncate_and_trailoff("aaaaaa", 7), "aaaaaa");
1078 assert_eq!(truncate_and_trailoff("aaaaaa", 6), "aaaaaa");
1079 assert_eq!(truncate_and_trailoff("aaaaaa", 5), "aaaaaβ¦");
1080 assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
1081 assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
1082 assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèèβ¦");
1083 }
1084
1085 #[test]
1086 fn test_truncate_and_remove_front() {
1087 assert_eq!(truncate_and_remove_front("", 5), "");
1088 assert_eq!(truncate_and_remove_front("aaaaaa", 7), "aaaaaa");
1089 assert_eq!(truncate_and_remove_front("aaaaaa", 6), "aaaaaa");
1090 assert_eq!(truncate_and_remove_front("aaaaaa", 5), "β¦aaaaa");
1091 assert_eq!(truncate_and_remove_front("èèèèèè", 7), "èèèèèè");
1092 assert_eq!(truncate_and_remove_front("èèèèèè", 6), "èèèèèè");
1093 assert_eq!(truncate_and_remove_front("èèèèèè", 5), "β¦Γ¨Γ¨Γ¨Γ¨Γ¨");
1094 }
1095
1096 #[test]
1097 fn test_numeric_prefix_str_method() {
1098 let target = "1a";
1099 assert_eq!(
1100 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1101 NumericPrefixWithSuffix(Some(1), "a")
1102 );
1103
1104 let target = "12ab";
1105 assert_eq!(
1106 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1107 NumericPrefixWithSuffix(Some(12), "ab")
1108 );
1109
1110 let target = "12_ab";
1111 assert_eq!(
1112 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1113 NumericPrefixWithSuffix(Some(12), "_ab")
1114 );
1115
1116 let target = "1_2ab";
1117 assert_eq!(
1118 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1119 NumericPrefixWithSuffix(Some(1), "_2ab")
1120 );
1121
1122 let target = "1.2";
1123 assert_eq!(
1124 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1125 NumericPrefixWithSuffix(Some(1), ".2")
1126 );
1127
1128 let target = "1.2_a";
1129 assert_eq!(
1130 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1131 NumericPrefixWithSuffix(Some(1), ".2_a")
1132 );
1133
1134 let target = "12.2_a";
1135 assert_eq!(
1136 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1137 NumericPrefixWithSuffix(Some(12), ".2_a")
1138 );
1139
1140 let target = "12a.2_a";
1141 assert_eq!(
1142 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1143 NumericPrefixWithSuffix(Some(12), "a.2_a")
1144 );
1145 }
1146
1147 #[test]
1148 fn test_numeric_prefix_with_suffix() {
1149 let mut sorted = vec!["1-abc", "10", "11def", "2", "21-abc"];
1150 sorted.sort_by_key(|s| NumericPrefixWithSuffix::from_numeric_prefixed_str(s));
1151 assert_eq!(sorted, ["1-abc", "2", "10", "11def", "21-abc"]);
1152
1153 for numeric_prefix_less in ["numeric_prefix_less", "aaa", "~β’Β£"] {
1154 assert_eq!(
1155 NumericPrefixWithSuffix::from_numeric_prefixed_str(numeric_prefix_less),
1156 NumericPrefixWithSuffix(None, numeric_prefix_less),
1157 "String without numeric prefix `{numeric_prefix_less}` should not be converted into NumericPrefixWithSuffix"
1158 )
1159 }
1160 }
1161
1162 #[test]
1163 fn test_word_consists_of_emojis() {
1164 let words_to_test = vec![
1165 ("π¨βπ©βπ§βπ§ππ₯", true),
1166 ("π", true),
1167 ("!π", false),
1168 ("π!", false),
1169 ("π ", false),
1170 (" π", false),
1171 ("Test", false),
1172 ];
1173
1174 for (text, expected_result) in words_to_test {
1175 assert_eq!(word_consists_of_emojis(text), expected_result);
1176 }
1177 }
1178
1179 #[test]
1180 fn test_truncate_lines_and_trailoff() {
1181 let text = r#"Line 1
1182Line 2
1183Line 3"#;
1184
1185 assert_eq!(
1186 truncate_lines_and_trailoff(text, 2),
1187 r#"Line 1
1188β¦"#
1189 );
1190
1191 assert_eq!(
1192 truncate_lines_and_trailoff(text, 3),
1193 r#"Line 1
1194Line 2
1195β¦"#
1196 );
1197
1198 assert_eq!(
1199 truncate_lines_and_trailoff(text, 4),
1200 r#"Line 1
1201Line 2
1202Line 3"#
1203 );
1204 }
1205
1206 #[test]
1207 fn test_expanded_and_wrapped_usize_range() {
1208 // Neither wrap
1209 assert_eq!(
1210 expanded_and_wrapped_usize_range(2..4, 1, 1, 8).collect::<Vec<usize>>(),
1211 (1..5).collect::<Vec<usize>>()
1212 );
1213 // Start wraps
1214 assert_eq!(
1215 expanded_and_wrapped_usize_range(2..4, 3, 1, 8).collect::<Vec<usize>>(),
1216 ((0..5).chain(7..8)).collect::<Vec<usize>>()
1217 );
1218 // Start wraps all the way around
1219 assert_eq!(
1220 expanded_and_wrapped_usize_range(2..4, 5, 1, 8).collect::<Vec<usize>>(),
1221 (0..8).collect::<Vec<usize>>()
1222 );
1223 // Start wraps all the way around and past 0
1224 assert_eq!(
1225 expanded_and_wrapped_usize_range(2..4, 10, 1, 8).collect::<Vec<usize>>(),
1226 (0..8).collect::<Vec<usize>>()
1227 );
1228 // End wraps
1229 assert_eq!(
1230 expanded_and_wrapped_usize_range(3..5, 1, 4, 8).collect::<Vec<usize>>(),
1231 (0..1).chain(2..8).collect::<Vec<usize>>()
1232 );
1233 // End wraps all the way around
1234 assert_eq!(
1235 expanded_and_wrapped_usize_range(3..5, 1, 5, 8).collect::<Vec<usize>>(),
1236 (0..8).collect::<Vec<usize>>()
1237 );
1238 // End wraps all the way around and past the end
1239 assert_eq!(
1240 expanded_and_wrapped_usize_range(3..5, 1, 10, 8).collect::<Vec<usize>>(),
1241 (0..8).collect::<Vec<usize>>()
1242 );
1243 // Both start and end wrap
1244 assert_eq!(
1245 expanded_and_wrapped_usize_range(3..5, 4, 4, 8).collect::<Vec<usize>>(),
1246 (0..8).collect::<Vec<usize>>()
1247 );
1248 }
1249
1250 #[test]
1251 fn test_wrapped_usize_outward_from() {
1252 // No wrapping
1253 assert_eq!(
1254 wrapped_usize_outward_from(4, 2, 2, 10).collect::<Vec<usize>>(),
1255 vec![4, 5, 3, 6, 2]
1256 );
1257 // Wrapping at end
1258 assert_eq!(
1259 wrapped_usize_outward_from(8, 2, 3, 10).collect::<Vec<usize>>(),
1260 vec![8, 9, 7, 0, 6, 1]
1261 );
1262 // Wrapping at start
1263 assert_eq!(
1264 wrapped_usize_outward_from(1, 3, 2, 10).collect::<Vec<usize>>(),
1265 vec![1, 2, 0, 3, 9, 8]
1266 );
1267 // All values wrap around
1268 assert_eq!(
1269 wrapped_usize_outward_from(5, 10, 10, 8).collect::<Vec<usize>>(),
1270 vec![5, 6, 4, 7, 3, 0, 2, 1]
1271 );
1272 // None before / after
1273 assert_eq!(
1274 wrapped_usize_outward_from(3, 0, 0, 8).collect::<Vec<usize>>(),
1275 vec![3]
1276 );
1277 // Starting point already wrapped
1278 assert_eq!(
1279 wrapped_usize_outward_from(15, 2, 2, 10).collect::<Vec<usize>>(),
1280 vec![5, 6, 4, 7, 3]
1281 );
1282 // wrap_length of 0
1283 assert_eq!(
1284 wrapped_usize_outward_from(4, 2, 2, 0).collect::<Vec<usize>>(),
1285 Vec::<usize>::new()
1286 );
1287 }
1288
1289 #[test]
1290 fn test_split_with_ranges() {
1291 let input = "hi";
1292 let result = split_str_with_ranges(input, |c| c == ' ');
1293
1294 assert_eq!(result.len(), 1);
1295 assert_eq!(result[0], (0..2, "hi"));
1296
1297 let input = "hΓ©lloπ¦world";
1298 let result = split_str_with_ranges(input, |c| c == 'π¦');
1299
1300 assert_eq!(result.len(), 2);
1301 assert_eq!(result[0], (0..6, "hΓ©llo")); // 'Γ©' is 2 bytes
1302 assert_eq!(result[1], (10..15, "world")); // 'π¦' is 4 bytes
1303 }
1304}