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