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