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