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
60pub fn truncate_and_trailoff(s: &str, max_chars: usize) -> String {
63 debug_assert!(max_chars >= 5);
64
65 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
77pub fn truncate_and_remove_front(s: &str, max_chars: usize) -> String {
80 debug_assert!(max_chars >= 5);
81
82 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
98pub 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
111pub 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
127pub 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 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 assert_eq!(truncate_lines_to_byte_limit(text, 100), text);
150
151 assert_eq!(truncate_lines_to_byte_limit(text, 7), "Line 1\n");
153
154 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 assert_eq!(truncate_lines_to_byte_limit(text, 6), "Line ");
160
161 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
175pub 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.clear();
204 }
205 if items.len() <= limit {
206 items.sort_by(compare);
207 return;
208 }
209 items.select_nth_unstable_by(limit, compare);
216 items.truncate(limit);
217 items.sort_by(compare);
218}
219
220#[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)]
246pub fn increase_open_file_limit() -> Result<()> {
247 use anyhow::Context as _;
248 use nix::sys::resource::{Resource::RLIMIT_NOFILE, getrlimit, setrlimit};
249
250 let (soft_limit, hard_limit) = getrlimit(RLIMIT_NOFILE).context("getrlimit(RLIMIT_NOFILE)")?;
251 let target = if cfg!(target_os = "macos") {
253 10_240
254 } else {
255 65_536
256 };
257 let mut requested_limit = hard_limit.min(target);
258
259 while requested_limit > soft_limit {
260 let Err(error) = setrlimit(RLIMIT_NOFILE, requested_limit, hard_limit) else {
261 log::info!("raised open file soft limit from {soft_limit} to {requested_limit}");
262 return Ok(());
263 };
264
265 if error != nix::errno::Errno::EINVAL || requested_limit == soft_limit + 1 {
267 return Err(error).context("setrlimit(RLIMIT_NOFILE)");
268 }
269 requested_limit = soft_limit + (requested_limit - soft_limit) / 2;
270 }
271
272 Ok(())
273}
274
275#[cfg(all(test, unix))]
276#[test]
277fn test_increase_open_file_limit() {
278 use nix::sys::resource::{Resource::RLIMIT_NOFILE, getrlimit};
279
280 let (soft_before, hard_before) = getrlimit(RLIMIT_NOFILE).unwrap();
281 increase_open_file_limit().expect("raising the open file soft limit should succeed");
282 let (soft_after, hard_after) = getrlimit(RLIMIT_NOFILE).unwrap();
283
284 assert!(
285 soft_after >= soft_before,
286 "soft limit must not decrease: {soft_before} -> {soft_after}"
287 );
288 assert_eq!(hard_after, hard_before, "hard limit must remain unchanged");
289}
290
291#[cfg(unix)]
292fn load_shell_from_passwd() -> Result<()> {
293 let buflen = match unsafe { libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) } {
294 n if n < 0 => 1024,
295 n => n as usize,
296 };
297 let mut buffer = Vec::with_capacity(buflen);
298
299 let mut pwd: std::mem::MaybeUninit<libc::passwd> = std::mem::MaybeUninit::uninit();
300 let mut result: *mut libc::passwd = std::ptr::null_mut();
301
302 let uid = unsafe { libc::getuid() };
303 let status = unsafe {
304 libc::getpwuid_r(
305 uid,
306 pwd.as_mut_ptr(),
307 buffer.as_mut_ptr() as *mut libc::c_char,
308 buflen,
309 &mut result,
310 )
311 };
312 anyhow::ensure!(!result.is_null(), "passwd entry for uid {} not found", uid);
313
314 let entry = unsafe { pwd.assume_init() };
316
317 anyhow::ensure!(
318 status == 0,
319 "call to getpwuid_r failed. uid: {}, status: {}",
320 uid,
321 status
322 );
323 anyhow::ensure!(
324 entry.pw_uid == uid,
325 "passwd entry has different uid ({}) than getuid ({}) returned",
326 entry.pw_uid,
327 uid,
328 );
329
330 let shell = unsafe { std::ffi::CStr::from_ptr(entry.pw_shell).to_str().unwrap() };
331 if env::var("SHELL").map_or(true, |shell_env| shell_env != shell) {
332 log::info!(
333 "updating SHELL environment variable to value from passwd entry: {:?}",
334 shell,
335 );
336 unsafe { env::set_var("SHELL", shell) };
337 }
338
339 Ok(())
340}
341
342pub fn get_shell_safe_zed_path() -> anyhow::Result<String> {
344 let zed_path =
345 std::env::current_exe().context("Failed to determine current zed executable path.")?;
346
347 zed_path
348 .try_shell_safe()
349 .context("Failed to shell-escape Zed executable path.")
350}
351
352pub fn get_zed_cli_path() -> Result<PathBuf> {
355 let zed_path =
356 std::env::current_exe().context("Failed to determine current zed executable path.")?;
357 let parent = zed_path
358 .parent()
359 .context("Failed to determine parent directory of zed executable path.")?;
360
361 let possible_locations: &[&str] = if cfg!(target_os = "macos") {
362 &["./cli"]
365 } else if cfg!(target_os = "windows") {
366 &["bin/zed.exe", "./cli.exe"]
368 } else if cfg!(target_os = "linux") || cfg!(target_os = "freebsd") {
369 &["../bin/zed", "./cli"]
371 } else {
372 anyhow::bail!("unsupported platform for determining zed-cli path");
373 };
374
375 possible_locations
376 .iter()
377 .find_map(|p| {
378 parent
379 .join(p)
380 .canonicalize()
381 .ok()
382 .filter(|p| p != &zed_path)
383 })
384 .with_context(|| {
385 format!(
386 "could not find zed-cli from any of: {}",
387 possible_locations.join(", ")
388 )
389 })
390}
391
392#[cfg(unix)]
393pub async fn load_login_shell_environment() -> Result<()> {
394 load_shell_from_passwd().log_err();
395
396 for (name, value) in shell_env::capture(get_system_shell(), &[], paths::home_dir()).await? {
402 unsafe { env::set_var(&name, &value) };
403 }
404
405 log::info!(
406 "set environment variables from shell:{}, path:{}",
407 std::env::var("SHELL").unwrap_or_default(),
408 std::env::var("PATH").unwrap_or_default(),
409 );
410
411 Ok(())
412}
413
414pub fn set_pre_exec_to_start_new_session(
419 command: &mut std::process::Command,
420) -> &mut std::process::Command {
421 #[cfg(not(target_os = "windows"))]
424 unsafe {
425 use std::os::unix::process::CommandExt;
426 command.pre_exec(|| {
427 libc::setsid();
428 Ok(())
429 });
430 };
431 command
432}
433
434pub fn merge_json_lenient_value_into(
435 source: serde_json_lenient::Value,
436 target: &mut serde_json_lenient::Value,
437) {
438 match (source, target) {
439 (serde_json_lenient::Value::Object(source), serde_json_lenient::Value::Object(target)) => {
440 for (key, value) in source {
441 if let Some(target) = target.get_mut(&key) {
442 merge_json_lenient_value_into(value, target);
443 } else {
444 target.insert(key, value);
445 }
446 }
447 }
448
449 (serde_json_lenient::Value::Array(source), serde_json_lenient::Value::Array(target)) => {
450 for value in source {
451 target.push(value);
452 }
453 }
454
455 (source, target) => *target = source,
456 }
457}
458
459pub fn merge_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
460 use serde_json::Value;
461
462 match (source, target) {
463 (Value::Object(source), Value::Object(target)) => {
464 for (key, value) in source {
465 if let Some(target) = target.get_mut(&key) {
466 merge_json_value_into(value, target);
467 } else {
468 target.insert(key, value);
469 }
470 }
471 }
472
473 (Value::Array(source), Value::Array(target)) => {
474 for value in source {
475 target.push(value);
476 }
477 }
478
479 (source, target) => *target = source,
480 }
481}
482
483pub fn union_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
484 use serde_json::Value;
485
486 match (source, target) {
487 (Value::Object(source), Value::Object(target)) => {
488 for (key, value) in source {
489 if let Some(target) = target.get_mut(&key) {
490 union_json_value_into(value, target);
491 } else {
492 target.insert(key, value);
493 }
494 }
495 }
496 (Value::Array(source), Value::Array(target)) => {
497 for value in source {
498 if !target.contains(&value) {
499 target.push(value);
500 }
501 }
502 }
503 (source, target) => *target = source,
504 }
505}
506
507pub fn merge_non_null_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
508 use serde_json::Value;
509 if let Value::Object(source_object) = source {
510 let target_object = if let Value::Object(target) = target {
511 target
512 } else {
513 *target = Value::Object(Default::default());
514 target.as_object_mut().unwrap()
515 };
516 for (key, value) in source_object {
517 if let Some(target) = target_object.get_mut(&key) {
518 merge_non_null_json_value_into(value, target);
519 } else if !value.is_null() {
520 target_object.insert(key, value);
521 }
522 }
523 } else if !source.is_null() {
524 *target = source
525 }
526}
527
528pub fn measure<R>(label: &str, f: impl FnOnce() -> R) -> R {
529 static ZED_MEASUREMENTS: OnceLock<bool> = OnceLock::new();
530 let zed_measurements = ZED_MEASUREMENTS.get_or_init(|| {
531 env::var("ZED_MEASUREMENTS")
532 .map(|measurements| measurements == "1" || measurements == "true")
533 .unwrap_or(false)
534 });
535
536 if *zed_measurements {
537 let start = Instant::now();
538 let result = f();
539 let elapsed = start.elapsed();
540 eprintln!("{}: {:?}", label, elapsed);
541 result
542 } else {
543 f()
544 }
545}
546
547pub fn expanded_and_wrapped_usize_range(
548 range: Range<usize>,
549 additional_before: usize,
550 additional_after: usize,
551 wrap_length: usize,
552) -> impl Iterator<Item = usize> {
553 let start_wraps = range.start < additional_before;
554 let end_wraps = wrap_length < range.end + additional_after;
555 if start_wraps && end_wraps {
556 Either::Left(0..wrap_length)
557 } else if start_wraps {
558 let wrapped_start = (range.start + wrap_length).saturating_sub(additional_before);
559 if wrapped_start <= range.end {
560 Either::Left(0..wrap_length)
561 } else {
562 Either::Right((0..range.end + additional_after).chain(wrapped_start..wrap_length))
563 }
564 } else if end_wraps {
565 let wrapped_end = range.end + additional_after - wrap_length;
566 if range.start <= wrapped_end {
567 Either::Left(0..wrap_length)
568 } else {
569 Either::Right((0..wrapped_end).chain(range.start - additional_before..wrap_length))
570 }
571 } else {
572 Either::Left((range.start - additional_before)..(range.end + additional_after))
573 }
574}
575
576pub fn wrapped_usize_outward_from(
580 start: usize,
581 additional_before: usize,
582 additional_after: usize,
583 wrap_length: usize,
584) -> impl Iterator<Item = usize> {
585 let mut count = 0;
586 let mut after_offset = 1;
587 let mut before_offset = 1;
588
589 std::iter::from_fn(move || {
590 count += 1;
591 if count > wrap_length {
592 None
593 } else if count == 1 {
594 Some(start % wrap_length)
595 } else if after_offset <= additional_after && after_offset <= before_offset {
596 let value = (start + after_offset) % wrap_length;
597 after_offset += 1;
598 Some(value)
599 } else if before_offset <= additional_before {
600 let value = (start + wrap_length - before_offset) % wrap_length;
601 before_offset += 1;
602 Some(value)
603 } else if after_offset <= additional_after {
604 let value = (start + after_offset) % wrap_length;
605 after_offset += 1;
606 Some(value)
607 } else {
608 None
609 }
610 })
611}
612
613pub trait ResultExt<E> {
614 type Ok;
615
616 fn log_err(self) -> Option<Self::Ok>;
617 fn debug_assert_ok(self, reason: &str) -> Self;
619 fn warn_on_err(self) -> Option<Self::Ok>;
620 fn log_with_level(self, level: log::Level) -> Option<Self::Ok>;
621 fn anyhow(self) -> anyhow::Result<Self::Ok>
622 where
623 E: Into<anyhow::Error>;
624}
625
626impl<T, E> ResultExt<E> for Result<T, E>
627where
628 E: std::fmt::Debug,
629{
630 type Ok = T;
631
632 #[track_caller]
633 fn log_err(self) -> Option<T> {
634 self.log_with_level(log::Level::Error)
635 }
636
637 #[track_caller]
638 fn debug_assert_ok(self, reason: &str) -> Self {
639 if let Err(error) = &self {
640 debug_panic!("{reason} - {error:?}");
641 }
642 self
643 }
644
645 #[track_caller]
646 fn warn_on_err(self) -> Option<T> {
647 self.log_with_level(log::Level::Warn)
648 }
649
650 #[track_caller]
651 fn log_with_level(self, level: log::Level) -> Option<T> {
652 match self {
653 Ok(value) => Some(value),
654 Err(error) => {
655 log_error_with_caller(*Location::caller(), error, level);
656 None
657 }
658 }
659 }
660
661 fn anyhow(self) -> anyhow::Result<T>
662 where
663 E: Into<anyhow::Error>,
664 {
665 self.map_err(Into::into)
666 }
667}
668
669fn log_error_with_caller<E>(caller: core::panic::Location<'_>, error: E, level: log::Level)
670where
671 E: std::fmt::Debug,
672{
673 #[cfg(not(target_os = "windows"))]
674 let file = caller.file();
675 #[cfg(target_os = "windows")]
676 let file = caller.file().replace('\\', "/");
677 let target = file
680 .split_once("crates/")
681 .and_then(|(_, s)| s.split_once("/src/"));
682
683 let module_path = target.map(|(krate, module)| {
684 krate.to_owned() + "::" + &module.trim_end_matches(".rs").replace('/', "::")
685 });
686 log::logger().log(
687 &log::Record::builder()
688 .target(target.map_or("", |(krate, _)| krate))
689 .module_path(module_path.as_deref())
690 .args(format_args!("{:?}", error))
691 .file(Some(caller.file()))
692 .line(Some(caller.line()))
693 .level(level)
694 .build(),
695 );
696}
697
698#[track_caller]
699pub fn log_err<E: std::fmt::Debug>(error: &E) {
700 log_error_with_caller(*Location::caller(), error, log::Level::Warn);
701}
702
703pub trait TryFutureExt {
704 fn log_err(self) -> LogErrorFuture<Self>
705 where
706 Self: Sized;
707
708 fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
709 where
710 Self: Sized;
711
712 fn warn_on_err(self) -> LogErrorFuture<Self>
713 where
714 Self: Sized;
715 fn unwrap(self) -> UnwrapFuture<Self>
716 where
717 Self: Sized;
718}
719
720impl<F, T, E> TryFutureExt for F
721where
722 F: Future<Output = Result<T, E>>,
723 E: std::fmt::Debug,
724{
725 #[track_caller]
726 fn log_err(self) -> LogErrorFuture<Self>
727 where
728 Self: Sized,
729 {
730 let location = Location::caller();
731 LogErrorFuture(self, log::Level::Error, *location)
732 }
733
734 fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
735 where
736 Self: Sized,
737 {
738 LogErrorFuture(self, log::Level::Error, location)
739 }
740
741 #[track_caller]
742 fn warn_on_err(self) -> LogErrorFuture<Self>
743 where
744 Self: Sized,
745 {
746 let location = Location::caller();
747 LogErrorFuture(self, log::Level::Warn, *location)
748 }
749
750 fn unwrap(self) -> UnwrapFuture<Self>
751 where
752 Self: Sized,
753 {
754 UnwrapFuture(self)
755 }
756}
757
758#[must_use]
759pub struct LogErrorFuture<F>(F, log::Level, core::panic::Location<'static>);
760
761impl<F, T, E> Future for LogErrorFuture<F>
762where
763 F: Future<Output = Result<T, E>>,
764 E: std::fmt::Debug,
765{
766 type Output = Option<T>;
767
768 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
769 let level = self.1;
770 let location = self.2;
771 let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
772 match inner.poll(cx) {
773 Poll::Ready(output) => Poll::Ready(match output {
774 Ok(output) => Some(output),
775 Err(error) => {
776 log_error_with_caller(location, error, level);
777 None
778 }
779 }),
780 Poll::Pending => Poll::Pending,
781 }
782 }
783}
784
785pub struct UnwrapFuture<F>(F);
786
787impl<F, T, E> Future for UnwrapFuture<F>
788where
789 F: Future<Output = Result<T, E>>,
790 E: std::fmt::Debug,
791{
792 type Output = T;
793
794 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
795 let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
796 match inner.poll(cx) {
797 Poll::Ready(result) => Poll::Ready(result.unwrap()),
798 Poll::Pending => Poll::Pending,
799 }
800 }
801}
802
803pub struct Deferred<F: FnOnce()>(Option<F>);
804
805impl<F: FnOnce()> Deferred<F> {
806 pub fn abort(mut self) {
808 self.0.take();
809 }
810}
811
812impl<F: FnOnce()> Drop for Deferred<F> {
813 fn drop(&mut self) {
814 if let Some(f) = self.0.take() {
815 f()
816 }
817 }
818}
819
820#[must_use]
822pub fn defer<F: FnOnce()>(f: F) -> Deferred<F> {
823 Deferred(Some(f))
824}
825
826#[cfg(any(test, feature = "test-support"))]
827mod rng {
828 use rand::prelude::*;
829
830 pub struct RandomCharIter<T: Rng> {
831 rng: T,
832 simple_text: bool,
833 }
834
835 impl<T: Rng> RandomCharIter<T> {
836 pub fn new(rng: T) -> Self {
837 Self {
838 rng,
839 simple_text: std::env::var("SIMPLE_TEXT").is_ok_and(|v| !v.is_empty()),
840 }
841 }
842
843 pub fn with_simple_text(mut self) -> Self {
844 self.simple_text = true;
845 self
846 }
847 }
848
849 impl<T: Rng> Iterator for RandomCharIter<T> {
850 type Item = char;
851
852 fn next(&mut self) -> Option<Self::Item> {
853 if self.simple_text {
854 return if self.rng.random_range(0..100) < 5 {
855 Some('\n')
856 } else {
857 Some(self.rng.random_range(b'a'..b'z' + 1).into())
858 };
859 }
860
861 match self.rng.random_range(0..100) {
862 0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.rng).copied(),
864 20..=32 => char::from_u32(self.rng.random_range(('α' as u32)..('ω' as u32 + 1))),
866 33..=45 => ['✋', '✅', '❌', '❎', '⭐']
868 .choose(&mut self.rng)
869 .copied(),
870 46..=58 => ['🍐', '🏀', '🍗', '🎉'].choose(&mut self.rng).copied(),
872 _ => Some(self.rng.random_range(b'a'..b'z' + 1).into()),
874 }
875 }
876 }
877}
878#[cfg(any(test, feature = "test-support"))]
879pub use rng::RandomCharIter;
880
881pub fn asset_str<A: rust_embed::RustEmbed>(path: &str) -> Cow<'static, str> {
883 match A::get(path).expect(path).data {
884 Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()),
885 Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()),
886 }
887}
888
889#[macro_export]
894macro_rules! maybe {
895 ($block:block) => {
896 (|| $block)()
897 };
898 (async $block:block) => {
899 (async || $block)()
900 };
901 (async move $block:block) => {
902 (async move || $block)()
903 };
904}
905
906pub trait RangeExt<T> {
907 fn sorted(&self) -> Self;
908 fn to_inclusive(&self) -> RangeInclusive<T>;
909 fn overlaps(&self, other: &Range<T>) -> bool;
910 fn contains_inclusive(&self, other: &Range<T>) -> bool;
911}
912
913impl<T: Ord + Clone> RangeExt<T> for Range<T> {
914 fn sorted(&self) -> Self {
915 cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
916 }
917
918 fn to_inclusive(&self) -> RangeInclusive<T> {
919 self.start.clone()..=self.end.clone()
920 }
921
922 fn overlaps(&self, other: &Range<T>) -> bool {
923 self.start < other.end && other.start < self.end
924 }
925
926 fn contains_inclusive(&self, other: &Range<T>) -> bool {
927 self.start <= other.start && other.end <= self.end
928 }
929}
930
931impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
932 fn sorted(&self) -> Self {
933 cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
934 }
935
936 fn to_inclusive(&self) -> RangeInclusive<T> {
937 self.clone()
938 }
939
940 fn overlaps(&self, other: &Range<T>) -> bool {
941 self.start() < &other.end && &other.start <= self.end()
942 }
943
944 fn contains_inclusive(&self, other: &Range<T>) -> bool {
945 self.start() <= &other.start && &other.end <= self.end()
946 }
947}
948
949#[derive(Debug, PartialEq, Eq)]
955pub struct NumericPrefixWithSuffix<'a>(Option<u64>, &'a str);
956
957impl<'a> NumericPrefixWithSuffix<'a> {
958 pub fn from_numeric_prefixed_str(str: &'a str) -> Self {
959 let i = str.chars().take_while(|c| c.is_ascii_digit()).count();
960 let (prefix, remainder) = str.split_at(i);
961
962 let prefix = prefix.parse().ok();
963 Self(prefix, remainder)
964 }
965}
966
967impl Ord for NumericPrefixWithSuffix<'_> {
970 fn cmp(&self, other: &Self) -> Ordering {
971 match (self.0, other.0) {
972 (None, None) => UniCase::new(self.1)
973 .cmp(&UniCase::new(other.1))
974 .then_with(|| self.1.cmp(other.1).reverse()),
975 (None, Some(_)) => Ordering::Greater,
976 (Some(_), None) => Ordering::Less,
977 (Some(a), Some(b)) => a.cmp(&b).then_with(|| {
978 UniCase::new(self.1)
979 .cmp(&UniCase::new(other.1))
980 .then_with(|| self.1.cmp(other.1).reverse())
981 }),
982 }
983 }
984}
985
986impl PartialOrd for NumericPrefixWithSuffix<'_> {
987 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
988 Some(self.cmp(other))
989 }
990}
991
992pub fn capitalize(str: &str) -> String {
1007 let mut chars = str.chars();
1008 match chars.next() {
1009 None => String::new(),
1010 Some(first_char) => first_char.to_uppercase().collect::<String>() + chars.as_str(),
1011 }
1012}
1013
1014fn emoji_regex() -> &'static Regex {
1015 static EMOJI_REGEX: LazyLock<Regex> =
1016 LazyLock::new(|| Regex::new("(\\p{Emoji}|\u{200D})").unwrap());
1017 &EMOJI_REGEX
1018}
1019
1020pub fn word_consists_of_emojis(s: &str) -> bool {
1023 let mut prev_end = 0;
1024 for capture in emoji_regex().find_iter(s) {
1025 if capture.start() != prev_end {
1026 return false;
1027 }
1028 prev_end = capture.end();
1029 }
1030 prev_end == s.len()
1031}
1032
1033pub fn split_str_with_ranges(s: &str, pat: impl Fn(char) -> bool) -> Vec<(Range<usize>, &str)> {
1036 let mut result = Vec::new();
1037 let mut start = 0;
1038
1039 for (i, ch) in s.char_indices() {
1040 if pat(ch) {
1041 if i > start {
1042 result.push((start..i, &s[start..i]));
1043 }
1044 start = i + ch.len_utf8();
1045 }
1046 }
1047
1048 if s.len() > start {
1049 result.push((start..s.len(), &s[start..s.len()]));
1050 }
1051
1052 result
1053}
1054
1055pub fn default<D: Default>() -> D {
1056 Default::default()
1057}
1058
1059#[cfg(windows)]
1060pub use self::shell::get_powershell;
1061pub use self::shell::{
1062 get_default_system_shell, get_default_system_shell_preferring_bash, get_system_shell,
1063};
1064
1065#[derive(Debug)]
1066pub enum ConnectionResult<O> {
1067 Timeout,
1068 ConnectionReset,
1069 Result(anyhow::Result<O>),
1070}
1071
1072impl<O> ConnectionResult<O> {
1073 pub fn into_response(self) -> anyhow::Result<O> {
1074 match self {
1075 ConnectionResult::Timeout => anyhow::bail!("Request timed out"),
1076 ConnectionResult::ConnectionReset => anyhow::bail!("Server reset the connection"),
1077 ConnectionResult::Result(r) => r,
1078 }
1079 }
1080}
1081
1082impl<O> From<anyhow::Result<O>> for ConnectionResult<O> {
1083 fn from(result: anyhow::Result<O>) -> Self {
1084 ConnectionResult::Result(result)
1085 }
1086}
1087
1088#[track_caller]
1089pub fn some_or_debug_panic<T>(option: Option<T>) -> Option<T> {
1090 #[cfg(debug_assertions)]
1091 if option.is_none() {
1092 panic!("Unexpected None");
1093 }
1094 option
1095}
1096
1097#[cfg(test)]
1098mod tests {
1099 use super::*;
1100
1101 #[test]
1102 fn test_extend_sorted() {
1103 let mut vec = vec![];
1104
1105 extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
1106 assert_eq!(vec, &[21, 17, 13, 8, 1]);
1107
1108 extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
1109 assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
1110
1111 extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
1112 assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
1113 }
1114
1115 #[test]
1116 fn test_truncate_to_bottom_n_sorted_by() {
1117 let mut vec: Vec<u32> = vec![5, 2, 3, 4, 1];
1118 truncate_to_bottom_n_sorted_by(&mut vec, 10, &u32::cmp);
1119 assert_eq!(vec, &[1, 2, 3, 4, 5]);
1120
1121 vec = vec![5, 2, 3, 4, 1];
1122 truncate_to_bottom_n_sorted_by(&mut vec, 5, &u32::cmp);
1123 assert_eq!(vec, &[1, 2, 3, 4, 5]);
1124
1125 vec = vec![5, 2, 3, 4, 1];
1126 truncate_to_bottom_n_sorted_by(&mut vec, 4, &u32::cmp);
1127 assert_eq!(vec, &[1, 2, 3, 4]);
1128
1129 vec = vec![5, 2, 3, 4, 1];
1130 truncate_to_bottom_n_sorted_by(&mut vec, 1, &u32::cmp);
1131 assert_eq!(vec, &[1]);
1132
1133 vec = vec![5, 2, 3, 4, 1];
1134 truncate_to_bottom_n_sorted_by(&mut vec, 0, &u32::cmp);
1135 assert!(vec.is_empty());
1136 }
1137
1138 #[test]
1139 fn test_iife() {
1140 fn option_returning_function() -> Option<()> {
1141 None
1142 }
1143
1144 let foo = maybe!({
1145 option_returning_function()?;
1146 Some(())
1147 });
1148
1149 assert_eq!(foo, None);
1150 }
1151
1152 #[test]
1153 fn test_truncate_and_trailoff() {
1154 assert_eq!(truncate_and_trailoff("", 5), "");
1155 assert_eq!(truncate_and_trailoff("aaaaaa", 7), "aaaaaa");
1156 assert_eq!(truncate_and_trailoff("aaaaaa", 6), "aaaaaa");
1157 assert_eq!(truncate_and_trailoff("aaaaaa", 5), "aaaaa…");
1158 assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
1159 assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
1160 assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèè…");
1161 }
1162
1163 #[test]
1164 fn test_truncate_and_remove_front() {
1165 assert_eq!(truncate_and_remove_front("", 5), "");
1166 assert_eq!(truncate_and_remove_front("aaaaaa", 7), "aaaaaa");
1167 assert_eq!(truncate_and_remove_front("aaaaaa", 6), "aaaaaa");
1168 assert_eq!(truncate_and_remove_front("aaaaaa", 5), "…aaaaa");
1169 assert_eq!(truncate_and_remove_front("èèèèèè", 7), "èèèèèè");
1170 assert_eq!(truncate_and_remove_front("èèèèèè", 6), "èèèèèè");
1171 assert_eq!(truncate_and_remove_front("èèèèèè", 5), "…èèèèè");
1172 }
1173
1174 #[test]
1175 fn test_numeric_prefix_str_method() {
1176 let target = "1a";
1177 assert_eq!(
1178 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1179 NumericPrefixWithSuffix(Some(1), "a")
1180 );
1181
1182 let target = "12ab";
1183 assert_eq!(
1184 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1185 NumericPrefixWithSuffix(Some(12), "ab")
1186 );
1187
1188 let target = "12_ab";
1189 assert_eq!(
1190 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1191 NumericPrefixWithSuffix(Some(12), "_ab")
1192 );
1193
1194 let target = "1_2ab";
1195 assert_eq!(
1196 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1197 NumericPrefixWithSuffix(Some(1), "_2ab")
1198 );
1199
1200 let target = "1.2";
1201 assert_eq!(
1202 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1203 NumericPrefixWithSuffix(Some(1), ".2")
1204 );
1205
1206 let target = "1.2_a";
1207 assert_eq!(
1208 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1209 NumericPrefixWithSuffix(Some(1), ".2_a")
1210 );
1211
1212 let target = "12.2_a";
1213 assert_eq!(
1214 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1215 NumericPrefixWithSuffix(Some(12), ".2_a")
1216 );
1217
1218 let target = "12a.2_a";
1219 assert_eq!(
1220 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1221 NumericPrefixWithSuffix(Some(12), "a.2_a")
1222 );
1223 }
1224
1225 #[test]
1226 fn test_numeric_prefix_with_suffix() {
1227 let mut sorted = vec!["1-abc", "10", "11def", "2", "21-abc"];
1228 sorted.sort_by_key(|s| NumericPrefixWithSuffix::from_numeric_prefixed_str(s));
1229 assert_eq!(sorted, ["1-abc", "2", "10", "11def", "21-abc"]);
1230
1231 for numeric_prefix_less in ["numeric_prefix_less", "aaa", "~™£"] {
1232 assert_eq!(
1233 NumericPrefixWithSuffix::from_numeric_prefixed_str(numeric_prefix_less),
1234 NumericPrefixWithSuffix(None, numeric_prefix_less),
1235 "String without numeric prefix `{numeric_prefix_less}` should not be converted into NumericPrefixWithSuffix"
1236 )
1237 }
1238 }
1239
1240 #[test]
1241 fn test_word_consists_of_emojis() {
1242 let words_to_test = vec![
1243 ("👨👩👧👧👋🥒", true),
1244 ("👋", true),
1245 ("!👋", false),
1246 ("👋!", false),
1247 ("👋 ", false),
1248 (" 👋", false),
1249 ("Test", false),
1250 ];
1251
1252 for (text, expected_result) in words_to_test {
1253 assert_eq!(word_consists_of_emojis(text), expected_result);
1254 }
1255 }
1256
1257 #[test]
1258 fn test_truncate_lines_and_trailoff() {
1259 let text = r#"Line 1
1260Line 2
1261Line 3"#;
1262
1263 assert_eq!(
1264 truncate_lines_and_trailoff(text, 2),
1265 r#"Line 1
1266…"#
1267 );
1268
1269 assert_eq!(
1270 truncate_lines_and_trailoff(text, 3),
1271 r#"Line 1
1272Line 2
1273…"#
1274 );
1275
1276 assert_eq!(
1277 truncate_lines_and_trailoff(text, 4),
1278 r#"Line 1
1279Line 2
1280Line 3"#
1281 );
1282 }
1283
1284 #[test]
1285 fn test_expanded_and_wrapped_usize_range() {
1286 assert_eq!(
1288 expanded_and_wrapped_usize_range(2..4, 1, 1, 8).collect::<Vec<usize>>(),
1289 (1..5).collect::<Vec<usize>>()
1290 );
1291 assert_eq!(
1293 expanded_and_wrapped_usize_range(2..4, 3, 1, 8).collect::<Vec<usize>>(),
1294 ((0..5).chain(7..8)).collect::<Vec<usize>>()
1295 );
1296 assert_eq!(
1298 expanded_and_wrapped_usize_range(2..4, 5, 1, 8).collect::<Vec<usize>>(),
1299 (0..8).collect::<Vec<usize>>()
1300 );
1301 assert_eq!(
1303 expanded_and_wrapped_usize_range(2..4, 10, 1, 8).collect::<Vec<usize>>(),
1304 (0..8).collect::<Vec<usize>>()
1305 );
1306 assert_eq!(
1308 expanded_and_wrapped_usize_range(3..5, 1, 4, 8).collect::<Vec<usize>>(),
1309 (0..1).chain(2..8).collect::<Vec<usize>>()
1310 );
1311 assert_eq!(
1313 expanded_and_wrapped_usize_range(3..5, 1, 5, 8).collect::<Vec<usize>>(),
1314 (0..8).collect::<Vec<usize>>()
1315 );
1316 assert_eq!(
1318 expanded_and_wrapped_usize_range(3..5, 1, 10, 8).collect::<Vec<usize>>(),
1319 (0..8).collect::<Vec<usize>>()
1320 );
1321 assert_eq!(
1323 expanded_and_wrapped_usize_range(3..5, 4, 4, 8).collect::<Vec<usize>>(),
1324 (0..8).collect::<Vec<usize>>()
1325 );
1326 }
1327
1328 #[test]
1329 fn test_wrapped_usize_outward_from() {
1330 assert_eq!(
1332 wrapped_usize_outward_from(4, 2, 2, 10).collect::<Vec<usize>>(),
1333 vec![4, 5, 3, 6, 2]
1334 );
1335 assert_eq!(
1337 wrapped_usize_outward_from(8, 2, 3, 10).collect::<Vec<usize>>(),
1338 vec![8, 9, 7, 0, 6, 1]
1339 );
1340 assert_eq!(
1342 wrapped_usize_outward_from(1, 3, 2, 10).collect::<Vec<usize>>(),
1343 vec![1, 2, 0, 3, 9, 8]
1344 );
1345 assert_eq!(
1347 wrapped_usize_outward_from(5, 10, 10, 8).collect::<Vec<usize>>(),
1348 vec![5, 6, 4, 7, 3, 0, 2, 1]
1349 );
1350 assert_eq!(
1352 wrapped_usize_outward_from(3, 0, 0, 8).collect::<Vec<usize>>(),
1353 vec![3]
1354 );
1355 assert_eq!(
1357 wrapped_usize_outward_from(15, 2, 2, 10).collect::<Vec<usize>>(),
1358 vec![5, 6, 4, 7, 3]
1359 );
1360 assert_eq!(
1362 wrapped_usize_outward_from(4, 2, 2, 0).collect::<Vec<usize>>(),
1363 Vec::<usize>::new()
1364 );
1365 }
1366
1367 #[test]
1368 fn test_split_with_ranges() {
1369 let input = "hi";
1370 let result = split_str_with_ranges(input, |c| c == ' ');
1371
1372 assert_eq!(result.len(), 1);
1373 assert_eq!(result[0], (0..2, "hi"));
1374
1375 let input = "héllo🦀world";
1376 let result = split_str_with_ranges(input, |c| c == '🦀');
1377
1378 assert_eq!(result.len(), 2);
1379 assert_eq!(result[0], (0..6, "héllo")); assert_eq!(result[1], (10..15, "world")); }
1382
1383 #[test]
1384 fn test_union_json_values() {
1385 use serde_json::json;
1386
1387 let mut target = json!({
1388 "unchanged": 1,
1389 "replaced_scalar": "old",
1390 "unioned_array": ["shared", "first"],
1391 "nested": {
1392 "kept": true,
1393 "plugins": [{ "name": "first-plugin" }],
1394 "scalar": 2,
1395 },
1396 });
1397 let source = json!({
1398 "replaced_scalar": "new",
1399 "unioned_array": ["shared", "second"],
1400 "inserted": ["brand-new"],
1401 "nested": {
1402 "plugins": [{ "name": "second-plugin" }],
1403 "scalar": 20,
1404 },
1405 });
1406
1407 union_json_value_into(source, &mut target);
1408
1409 assert_eq!(
1410 target,
1411 json!({
1412 "unchanged": 1,
1413 "replaced_scalar": "new",
1414 "unioned_array": ["shared", "first", "second"],
1415 "inserted": ["brand-new"],
1416 "nested": {
1417 "kept": true,
1418 "plugins": [{ "name": "first-plugin" }, { "name": "second-plugin" }],
1419 "scalar": 20,
1420 },
1421 })
1422 );
1423 }
1424}