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