1#[cfg(test)]
2extern crate self as util;
3
4#[cfg(not(target_family = "wasm"))]
5pub mod archive;
6#[cfg(not(target_family = "wasm"))]
7pub mod command;
8#[cfg(not(target_family = "wasm"))]
9pub mod fs;
10#[cfg(not(target_family = "wasm"))]
11pub mod process;
12#[cfg(not(target_family = "wasm"))]
13pub mod shell;
14#[cfg(not(target_family = "wasm"))]
15pub mod shell_builder;
16#[cfg(not(target_family = "wasm"))]
17pub mod shell_env;
18
19pub mod disambiguate;
20pub mod markdown;
21pub mod path_list;
22pub mod paths;
23pub mod redact;
24pub mod schemars;
25pub mod serde;
26pub mod size;
27#[cfg(any(test, feature = "test-support"))]
28pub mod test;
29pub mod time;
30
31use anyhow::Result;
32use itertools::Either;
33use regex::Regex;
34use std::path::PathBuf;
35use std::sync::LazyLock;
36use std::{
37 borrow::Cow,
38 cmp::{self, Ordering},
39 ops::{Range, RangeInclusive},
40};
41use unicase::UniCase;
42
43pub use gpui_util::*;
44pub use path::PathExt;
45pub use path::normalize_path;
46pub use path::rel_path;
47
48#[cfg(any(test, feature = "test-support"))]
49pub use util_macros::{line_endings, path, uri};
50
51#[cfg(not(target_family = "wasm"))]
52pub use self::shell::{
53 get_default_system_shell, get_default_system_shell_preferring_bash, get_system_shell,
54};
55
56pub fn truncate(s: &str, max_chars: usize) -> &str {
57 match s.char_indices().nth(max_chars) {
58 None => s,
59 Some((idx, _)) => &s[..idx],
60 }
61}
62
63pub fn parse_os_release(content: &str) -> Option<String> {
70 let mut id = None;
71 let mut version_id = None;
72 for line in content.lines() {
73 match line.split_once('=') {
74 Some(("ID", value)) => id = Some(value.trim_matches('"')),
75 Some(("VERSION_ID", value)) => version_id = Some(value.trim_matches('"')),
76 _ => {}
77 }
78 }
79 let id = id?;
80 Some(match version_id {
81 Some(version) => format!("{id} {version}"),
82 None => id.to_string(),
83 })
84}
85
86pub fn truncate_and_trailoff(s: &str, max_chars: usize) -> String {
89 debug_assert!(max_chars >= 5);
90
91 if s.len() <= max_chars {
94 return s.to_string();
95 }
96 let truncation_ix = s.char_indices().map(|(i, _)| i).nth(max_chars);
97 match truncation_ix {
98 Some(index) => s[..index].to_string() + "…",
99 _ => s.to_string(),
100 }
101}
102
103pub fn truncate_and_remove_front(s: &str, max_chars: usize) -> String {
106 debug_assert!(max_chars >= 5);
107
108 if s.len() <= max_chars {
111 return s.to_string();
112 }
113 let suffix_char_length = max_chars.saturating_sub(1);
114 let truncation_ix = s
115 .char_indices()
116 .map(|(i, _)| i)
117 .nth_back(suffix_char_length);
118 match truncation_ix {
119 Some(index) if index > 0 => "…".to_string() + &s[index..],
120 _ => s.to_string(),
121 }
122}
123
124pub fn truncate_lines_and_trailoff(s: &str, max_lines: usize) -> String {
128 let mut lines = s.lines().take(max_lines).collect::<Vec<_>>();
129 if lines.len() > max_lines - 1 {
130 lines.pop();
131 lines.join("\n") + "\n…"
132 } else {
133 lines.join("\n")
134 }
135}
136
137pub fn truncate_to_byte_limit(s: &str, max_bytes: usize) -> &str {
140 if s.len() < max_bytes {
141 return s;
142 }
143
144 for i in (0..max_bytes).rev() {
145 if s.is_char_boundary(i) {
146 return &s[..i];
147 }
148 }
149
150 ""
151}
152
153pub fn truncate_lines_to_byte_limit(s: &str, max_bytes: usize) -> &str {
156 if s.len() < max_bytes {
157 return s;
158 }
159
160 for i in (0..max_bytes).rev() {
161 if s.is_char_boundary(i) && s.as_bytes()[i] == b'\n' {
162 return &s[..i + 1];
164 }
165 }
166
167 truncate_to_byte_limit(s, max_bytes)
168}
169
170#[test]
171fn test_truncate_lines_to_byte_limit() {
172 let text = "Line 1\nLine 2\nLine 3\nLine 4";
173
174 assert_eq!(truncate_lines_to_byte_limit(text, 100), text);
176
177 assert_eq!(truncate_lines_to_byte_limit(text, 7), "Line 1\n");
179
180 assert_eq!(truncate_lines_to_byte_limit(text, 13), "Line 1\n");
182 assert_eq!(truncate_lines_to_byte_limit(text, 20), "Line 1\nLine 2\n");
183
184 assert_eq!(truncate_lines_to_byte_limit(text, 6), "Line ");
186
187 let text_utf8 = "Line 1\nLíne 2\nLine 3";
189 assert_eq!(
190 truncate_lines_to_byte_limit(text_utf8, 15),
191 "Line 1\nLíne 2\n"
192 );
193}
194
195pub fn extend_sorted<T, I, F>(vec: &mut Vec<T>, new_items: I, limit: usize, mut cmp: F)
199where
200 I: IntoIterator<Item = T>,
201 F: FnMut(&T, &T) -> Ordering,
202{
203 let mut start_index = 0;
204 for new_item in new_items {
205 if let Err(i) = vec[start_index..].binary_search_by(|m| cmp(m, &new_item)) {
206 let index = start_index + i;
207 if vec.len() < limit {
208 vec.insert(index, new_item);
209 } else if index < vec.len() {
210 vec.pop();
211 vec.insert(index, new_item);
212 }
213 start_index = index;
214 }
215 }
216}
217
218#[cfg(unix)]
224pub fn prevent_root_execution() {
225 let is_root = nix::unistd::geteuid().is_root();
226 let allow_root = std::env::var("ZED_ALLOW_ROOT").is_ok_and(|val| val == "true");
227
228 if is_root && !allow_root {
229 eprintln!(
230 "\
231Error: Running Zed as root or via sudo is unsupported.
232 Doing so (even once) may subtly break things for all subsequent non-root usage of Zed.
233 It is untested and not recommended, don't complain when things break.
234 If you wish to proceed anyways, set `ZED_ALLOW_ROOT=true` in your environment."
235 );
236 std::process::exit(1);
237 }
238}
239
240#[cfg(unix)]
244pub fn increase_open_file_limit() -> Result<()> {
245 use anyhow::Context as _;
246 use nix::sys::resource::{Resource::RLIMIT_NOFILE, getrlimit, setrlimit};
247
248 let (soft_limit, hard_limit) = getrlimit(RLIMIT_NOFILE).context("getrlimit(RLIMIT_NOFILE)")?;
249 let target = if cfg!(target_os = "macos") {
251 10_240
252 } else {
253 65_536
254 };
255 let mut requested_limit = hard_limit.min(target);
256
257 while requested_limit > soft_limit {
258 let Err(error) = setrlimit(RLIMIT_NOFILE, requested_limit, hard_limit) else {
259 log::info!("raised open file soft limit from {soft_limit} to {requested_limit}");
260 return Ok(());
261 };
262
263 if error != nix::errno::Errno::EINVAL || requested_limit == soft_limit + 1 {
265 return Err(error).context("setrlimit(RLIMIT_NOFILE)");
266 }
267 requested_limit = soft_limit + (requested_limit - soft_limit) / 2;
268 }
269
270 Ok(())
271}
272
273#[cfg(unix)]
274fn load_shell_from_passwd() -> Result<()> {
275 let buflen = match unsafe { libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) } {
276 n if n < 0 => 1024,
277 n => n as usize,
278 };
279 let mut buffer = Vec::with_capacity(buflen);
280
281 let mut pwd: std::mem::MaybeUninit<libc::passwd> = std::mem::MaybeUninit::uninit();
282 let mut result: *mut libc::passwd = std::ptr::null_mut();
283
284 let uid = unsafe { libc::getuid() };
285 let status = unsafe {
286 libc::getpwuid_r(
287 uid,
288 pwd.as_mut_ptr(),
289 buffer.as_mut_ptr() as *mut libc::c_char,
290 buflen,
291 &mut result,
292 )
293 };
294 anyhow::ensure!(!result.is_null(), "passwd entry for uid {} not found", uid);
295
296 let entry = unsafe { pwd.assume_init() };
298
299 anyhow::ensure!(
300 status == 0,
301 "call to getpwuid_r failed. uid: {}, status: {}",
302 uid,
303 status
304 );
305 anyhow::ensure!(
306 entry.pw_uid == uid,
307 "passwd entry has different uid ({}) than getuid ({}) returned",
308 entry.pw_uid,
309 uid,
310 );
311
312 let shell = unsafe { std::ffi::CStr::from_ptr(entry.pw_shell).to_str().unwrap() };
313 let should_set_shell = std::env::var("SHELL").map_or(true, |shell_env| {
314 shell_env != shell && !std::path::Path::new(&shell_env).exists()
315 });
316
317 if should_set_shell {
318 log::info!(
319 "updating SHELL environment variable to value from passwd entry: {:?}",
320 shell,
321 );
322 unsafe { std::env::set_var("SHELL", shell) };
323 }
324
325 Ok(())
326}
327
328#[cfg(not(target_family = "wasm"))]
330pub fn get_shell_safe_zed_path(shell_kind: shell::ShellKind) -> anyhow::Result<String> {
331 use anyhow::Context as _;
332 use paths::PathExt;
333 let mut zed_path =
334 std::env::current_exe().context("Failed to determine current zed executable path.")?;
335 if cfg!(target_os = "linux")
336 && !zed_path.is_file()
337 && let Some(truncated) = zed_path
338 .clone()
339 .file_name()
340 .and_then(|s| s.to_str())
341 .and_then(|n| n.strip_suffix(" (deleted)"))
342 {
343 zed_path.set_file_name(truncated);
345 }
346
347 zed_path
348 .try_shell_safe(shell_kind)
349 .context("Failed to shell-escape Zed executable path.")
350}
351
352pub fn get_zed_cli_path() -> Result<PathBuf> {
355 use anyhow::Context as _;
356 let zed_path =
357 std::env::current_exe().context("Failed to determine current zed executable path.")?;
358 let parent = zed_path
359 .parent()
360 .context("Failed to determine parent directory of zed executable path.")?;
361
362 let possible_locations: &[&str] = if cfg!(target_os = "macos") {
363 &["./cli"]
366 } else if cfg!(target_os = "windows") {
367 &["bin/zed.exe", "./cli.exe"]
369 } else if cfg!(target_os = "linux") || cfg!(target_os = "freebsd") {
370 &["../bin/zed", "./cli"]
372 } else {
373 anyhow::bail!("unsupported platform for determining zed-cli path");
374 };
375
376 possible_locations
377 .iter()
378 .find_map(|p| {
379 parent
380 .join(p)
381 .canonicalize()
382 .ok()
383 .filter(|p| p != &zed_path)
384 })
385 .with_context(|| {
386 format!(
387 "could not find zed-cli from any of: {}",
388 possible_locations.join(", ")
389 )
390 })
391}
392
393#[cfg(unix)]
394pub async fn load_login_shell_environment() -> Result<()> {
395 use anyhow::Context as _;
396
397 load_shell_from_passwd().log_err();
398
399 for (name, value) in shell_env::capture(get_system_shell(), &[], paths::home_dir())
405 .await
406 .with_context(|| format!("capturing environment with {:?}", get_system_shell()))?
407 {
408 if name == "SHLVL" {
413 continue;
414 }
415 unsafe { std::env::set_var(&name, &value) };
416 }
417
418 log::info!(
419 "set environment variables from shell:{}, path:{}",
420 std::env::var("SHELL").unwrap_or_default(),
421 std::env::var("PATH").unwrap_or_default(),
422 );
423
424 Ok(())
425}
426
427pub fn set_pre_exec_to_start_new_session(
432 command: &mut std::process::Command,
433) -> &mut std::process::Command {
434 #[cfg(unix)]
437 unsafe {
438 use std::os::unix::process::CommandExt;
439 command.pre_exec(|| {
440 libc::setsid();
441 Ok(())
442 });
443 };
444 command
445}
446
447pub fn merge_json_lenient_value_into(
448 source: serde_json_lenient::Value,
449 target: &mut serde_json_lenient::Value,
450) {
451 match (source, target) {
452 (serde_json_lenient::Value::Object(source), serde_json_lenient::Value::Object(target)) => {
453 for (key, value) in source {
454 if let Some(target) = target.get_mut(&key) {
455 merge_json_lenient_value_into(value, target);
456 } else {
457 target.insert(key, value);
458 }
459 }
460 }
461
462 (serde_json_lenient::Value::Array(source), serde_json_lenient::Value::Array(target)) => {
463 for value in source {
464 target.push(value);
465 }
466 }
467
468 (source, target) => *target = source,
469 }
470}
471
472pub fn merge_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
476 use serde_json::Value;
477
478 match (source, target) {
479 (Value::Object(source), Value::Object(target)) => {
480 for (key, value) in source {
481 if let Some(target) = target.get_mut(&key) {
482 merge_json_value_into(value, target);
483 } else {
484 target.insert(key, value);
485 }
486 }
487 }
488 (source, target) => *target = source,
489 }
490}
491
492pub fn union_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
493 use serde_json::Value;
494
495 match (source, target) {
496 (Value::Object(source), Value::Object(target)) => {
497 for (key, value) in source {
498 if let Some(target) = target.get_mut(&key) {
499 union_json_value_into(value, target);
500 } else {
501 target.insert(key, value);
502 }
503 }
504 }
505 (Value::Array(source), Value::Array(target)) => {
506 for value in source {
507 if !target.contains(&value) {
508 target.push(value);
509 }
510 }
511 }
512 (source, target) => *target = source,
513 }
514}
515
516pub fn merge_non_null_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
517 use serde_json::Value;
518 if let Value::Object(source_object) = source {
519 let target_object = if let Value::Object(target) = target {
520 target
521 } else {
522 *target = Value::Object(Default::default());
523 target.as_object_mut().unwrap()
524 };
525 for (key, value) in source_object {
526 if let Some(target) = target_object.get_mut(&key) {
527 merge_non_null_json_value_into(value, target);
528 } else if !value.is_null() {
529 target_object.insert(key, value);
530 }
531 }
532 } else if !source.is_null() {
533 *target = source
534 }
535}
536
537pub fn expanded_and_wrapped_usize_range(
538 range: Range<usize>,
539 additional_before: usize,
540 additional_after: usize,
541 wrap_length: usize,
542) -> impl Iterator<Item = usize> {
543 let start_wraps = range.start < additional_before;
544 let end_wraps = wrap_length < range.end + additional_after;
545 if start_wraps && end_wraps {
546 Either::Left(0..wrap_length)
547 } else if start_wraps {
548 let wrapped_start = (range.start + wrap_length).saturating_sub(additional_before);
549 if wrapped_start <= range.end {
550 Either::Left(0..wrap_length)
551 } else {
552 Either::Right((0..range.end + additional_after).chain(wrapped_start..wrap_length))
553 }
554 } else if end_wraps {
555 let wrapped_end = range.end + additional_after - wrap_length;
556 if range.start <= wrapped_end {
557 Either::Left(0..wrap_length)
558 } else {
559 Either::Right((0..wrapped_end).chain(range.start - additional_before..wrap_length))
560 }
561 } else {
562 Either::Left((range.start - additional_before)..(range.end + additional_after))
563 }
564}
565
566pub fn wrapped_usize_outward_from(
570 start: usize,
571 additional_before: usize,
572 additional_after: usize,
573 wrap_length: usize,
574) -> impl Iterator<Item = usize> {
575 let mut count = 0;
576 let mut after_offset = 1;
577 let mut before_offset = 1;
578
579 std::iter::from_fn(move || {
580 count += 1;
581 if count > wrap_length {
582 None
583 } else if count == 1 {
584 Some(start % wrap_length)
585 } else if after_offset <= additional_after && after_offset <= before_offset {
586 let value = (start + after_offset) % wrap_length;
587 after_offset += 1;
588 Some(value)
589 } else if before_offset <= additional_before {
590 let value = (start + wrap_length - before_offset) % wrap_length;
591 before_offset += 1;
592 Some(value)
593 } else if after_offset <= additional_after {
594 let value = (start + after_offset) % wrap_length;
595 after_offset += 1;
596 Some(value)
597 } else {
598 None
599 }
600 })
601}
602
603#[cfg(any(test, feature = "test-support"))]
604mod rng {
605 use rand::prelude::*;
606
607 pub struct RandomCharIter<T: Rng> {
608 rng: T,
609 simple_text: bool,
610 }
611
612 impl<T: Rng> RandomCharIter<T> {
613 pub fn new(rng: T) -> Self {
614 Self {
615 rng,
616 simple_text: std::env::var("SIMPLE_TEXT").is_ok_and(|v| !v.is_empty()),
617 }
618 }
619
620 pub fn with_simple_text(mut self) -> Self {
621 self.simple_text = true;
622 self
623 }
624 }
625
626 impl<T: Rng> Iterator for RandomCharIter<T> {
627 type Item = char;
628
629 fn next(&mut self) -> Option<Self::Item> {
630 if self.simple_text {
631 return if self.rng.random_range(0..100) < 5 {
632 Some('\n')
633 } else {
634 Some(self.rng.random_range(b'a'..b'z' + 1).into())
635 };
636 }
637
638 match self.rng.random_range(0..100) {
639 0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.rng).copied(),
641 20..=32 => char::from_u32(self.rng.random_range(('α' as u32)..('ω' as u32 + 1))),
643 33..=45 => ['✋', '✅', '❌', '❎', '⭐']
645 .choose(&mut self.rng)
646 .copied(),
647 46..=58 => ['🍐', '🏀', '🍗', '🎉'].choose(&mut self.rng).copied(),
649 _ => Some(self.rng.random_range(b'a'..b'z' + 1).into()),
651 }
652 }
653 }
654}
655#[cfg(any(test, feature = "test-support"))]
656pub use rng::RandomCharIter;
657
658pub fn asset_str<A: rust_embed::RustEmbed>(path: &str) -> Cow<'static, str> {
660 match A::get(path).expect(path).data {
661 Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()),
662 Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()),
663 }
664}
665
666pub fn dev_repo_root() -> Option<&'static std::path::Path> {
683 use std::path::PathBuf;
684 static ROOT: std::sync::OnceLock<Option<PathBuf>> = std::sync::OnceLock::new();
685 ROOT.get_or_init(|| {
686 let exe = std::env::current_exe().ok();
687 let candidates = [
688 exe.clone(),
689 exe.and_then(|exe| exe.canonicalize().ok()),
690 std::env::current_dir().ok(),
691 ];
692 candidates.into_iter().flatten().find_map(|start| {
693 Some(
694 start
695 .ancestors()
696 .find(|dir| dir.join(".git").exists())?
697 .to_path_buf(),
698 )
699 })
700 })
701 .as_deref()
702}
703
704#[doc(hidden)]
708pub mod __rust_embed {
709 pub use rust_embed::{EmbeddedFile, Filenames, Metadata, RustEmbed, flate, utils};
710}
711
712#[cfg(all(debug_assertions, not(feature = "debug-embed")))]
717#[doc(hidden)]
718pub fn __fs_embed_iter(
719 root_relative: &str,
720 includes: &[&str],
721 excludes: &[&str],
722) -> impl Iterator<Item = std::borrow::Cow<'static, str>> + 'static {
723 fs_embed_file_names(root_relative, includes, excludes)
724 .into_iter()
725 .map(std::borrow::Cow::Owned)
726}
727
728#[cfg(all(debug_assertions, not(feature = "debug-embed")))]
729fn fs_embed_file_names(root_relative: &str, includes: &[&str], excludes: &[&str]) -> Vec<String> {
730 let Some(root) = dev_repo_root().map(|root| root.join(root_relative)) else {
731 return Vec::new();
732 };
733 let matcher = rust_embed::utils::PathMatcher::new(includes, excludes);
734 rust_embed::utils::get_files(root.to_string_lossy().into_owned(), matcher)
735 .map(|entry| entry.rel_path)
736 .collect()
737}
738
739#[cfg(all(debug_assertions, not(feature = "debug-embed")))]
743#[doc(hidden)]
744pub fn __fs_embed_get(
745 root_relative: &str,
746 file_path: &str,
747 includes: &[&str],
748 excludes: &[&str],
749) -> Option<rust_embed::EmbeddedFile> {
750 let matcher = rust_embed::utils::PathMatcher::new(includes, excludes);
751 if !matcher.is_path_included(file_path) {
752 return None;
753 }
754 let root = dev_repo_root()
755 .expect("dev asset loading requires running from within the checkout")
756 .join(root_relative);
757 rust_embed::utils::read_file_from_fs(&root.join(file_path)).ok()
758}
759
760#[cfg(feature = "debug-embed")]
761#[doc(hidden)]
762#[macro_export]
763macro_rules! __fs_embed {
764 (
765 $vis:vis struct $name:ident,
766 crate_relative = $crate_relative:literal,
767 root_relative = $root_relative:literal
768 $(, include = [$($include:literal),* $(,)?])?
769 $(, exclude = [$($exclude:literal),* $(,)?])?
770 $(,)?
771 ) => {
772 #[derive($crate::__rust_embed::RustEmbed)]
773 #[crate_path = "::util::__rust_embed"]
774 #[folder = $crate_relative]
775 $($(#[include = $include])*)?
776 $($(#[exclude = $exclude])*)?
777 $vis struct $name;
778 };
779}
780
781#[cfg(not(feature = "debug-embed"))]
782#[doc(hidden)]
783#[macro_export]
784macro_rules! __fs_embed {
785 (
786 $vis:vis struct $name:ident,
787 crate_relative = $crate_relative:literal,
788 root_relative = $root_relative:literal
789 $(, include = [$($include:literal),* $(,)?])?
790 $(, exclude = [$($exclude:literal),* $(,)?])?
791 $(,)?
792 ) => {
793 #[cfg(not(debug_assertions))]
796 #[derive($crate::__rust_embed::RustEmbed)]
797 #[crate_path = "::util::__rust_embed"]
798 #[folder = $crate_relative]
799 $($(#[include = $include])*)?
800 $($(#[exclude = $exclude])*)?
801 $vis struct $name;
802
803 #[cfg(debug_assertions)]
804 $vis struct $name;
805
806 #[cfg(debug_assertions)]
811 impl $name {
812 pub fn get(
813 file_path: &str,
814 ) -> ::core::option::Option<$crate::__rust_embed::EmbeddedFile> {
815 $crate::__fs_embed_get(
816 $root_relative,
817 file_path,
818 &[$($($include),*)?],
819 &[$($($exclude),*)?],
820 )
821 }
822
823 pub fn iter(
824 ) -> impl ::core::iter::Iterator<Item = ::std::borrow::Cow<'static, str>> + 'static
825 {
826 $crate::__fs_embed_iter(
827 $root_relative,
828 &[$($($include),*)?],
829 &[$($($exclude),*)?],
830 )
831 }
832 }
833
834 #[cfg(debug_assertions)]
835 impl $crate::__rust_embed::RustEmbed for $name {
836 fn get(
837 file_path: &str,
838 ) -> ::core::option::Option<$crate::__rust_embed::EmbeddedFile> {
839 <$name>::get(file_path)
840 }
841
842 fn iter(
843 ) -> impl ::core::iter::Iterator<Item = ::std::borrow::Cow<'static, str>> + 'static
844 {
845 $crate::__fs_embed_iter(
846 $root_relative,
847 &[$($($include),*)?],
848 &[$($($exclude),*)?],
849 )
850 }
851 }
852 };
853}
854
855#[macro_export]
883macro_rules! fs_embed {
884 ($($tokens:tt)*) => {
885 $crate::__fs_embed!($($tokens)*);
886 };
887}
888
889pub trait RangeExt<T> {
890 fn sorted(&self) -> Self;
891 fn to_inclusive(&self) -> RangeInclusive<T>;
892 fn overlaps(&self, other: &Range<T>) -> bool;
893 fn contains_inclusive(&self, other: &Range<T>) -> bool;
894}
895
896impl<T: Ord + Clone> RangeExt<T> for Range<T> {
897 fn sorted(&self) -> Self {
898 cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
899 }
900
901 fn to_inclusive(&self) -> RangeInclusive<T> {
902 self.start.clone()..=self.end.clone()
903 }
904
905 fn overlaps(&self, other: &Range<T>) -> bool {
906 self.start < other.end && other.start < self.end
907 }
908
909 fn contains_inclusive(&self, other: &Range<T>) -> bool {
910 self.start <= other.start && other.end <= self.end
911 }
912}
913
914impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
915 fn sorted(&self) -> Self {
916 cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
917 }
918
919 fn to_inclusive(&self) -> RangeInclusive<T> {
920 self.clone()
921 }
922
923 fn overlaps(&self, other: &Range<T>) -> bool {
924 self.start() < &other.end && &other.start <= self.end()
925 }
926
927 fn contains_inclusive(&self, other: &Range<T>) -> bool {
928 self.start() <= &other.start && &other.end <= self.end()
929 }
930}
931
932#[derive(Debug, PartialEq, Eq)]
938pub struct NumericPrefixWithSuffix<'a>(Option<u64>, &'a str);
939
940impl<'a> NumericPrefixWithSuffix<'a> {
941 pub fn from_numeric_prefixed_str(str: &'a str) -> Self {
942 let i = str.chars().take_while(|c| c.is_ascii_digit()).count();
943 let (prefix, remainder) = str.split_at(i);
944
945 let prefix = prefix.parse().ok();
946 Self(prefix, remainder)
947 }
948}
949
950impl Ord for NumericPrefixWithSuffix<'_> {
953 fn cmp(&self, other: &Self) -> Ordering {
954 match (self.0, other.0) {
955 (None, None) => UniCase::new(self.1)
956 .cmp(&UniCase::new(other.1))
957 .then_with(|| self.1.cmp(other.1).reverse()),
958 (None, Some(_)) => Ordering::Greater,
959 (Some(_), None) => Ordering::Less,
960 (Some(a), Some(b)) => a.cmp(&b).then_with(|| {
961 UniCase::new(self.1)
962 .cmp(&UniCase::new(other.1))
963 .then_with(|| self.1.cmp(other.1).reverse())
964 }),
965 }
966 }
967}
968
969impl PartialOrd for NumericPrefixWithSuffix<'_> {
970 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
971 Some(self.cmp(other))
972 }
973}
974
975fn emoji_regex() -> &'static Regex {
976 static EMOJI_REGEX: LazyLock<Regex> =
977 LazyLock::new(|| Regex::new("(\\p{Emoji}|\u{200D})").unwrap());
978 &EMOJI_REGEX
979}
980
981pub fn word_consists_of_emojis(s: &str) -> bool {
984 let mut prev_end = 0;
985 for capture in emoji_regex().find_iter(s) {
986 if capture.start() != prev_end {
987 return false;
988 }
989 prev_end = capture.end();
990 }
991 prev_end == s.len()
992}
993
994pub fn split_str_with_ranges<'s>(
997 s: &'s str,
998 pat: &dyn Fn(char) -> bool,
999) -> Vec<(Range<usize>, &'s str)> {
1000 let mut result = Vec::new();
1001 let mut start = 0;
1002
1003 for (i, ch) in s.char_indices() {
1004 if pat(ch) {
1005 if i > start {
1006 result.push((start..i, &s[start..i]));
1007 }
1008 start = i + ch.len_utf8();
1009 }
1010 }
1011
1012 if s.len() > start {
1013 result.push((start..s.len(), &s[start..s.len()]));
1014 }
1015
1016 result
1017}
1018
1019pub fn default<D: Default>() -> D {
1020 Default::default()
1021}
1022
1023#[derive(Debug)]
1024pub enum ConnectionResult<O> {
1025 Timeout,
1026 ConnectionReset,
1027 Result(anyhow::Result<O>),
1028}
1029
1030impl<O> ConnectionResult<O> {
1031 pub fn into_response(self) -> anyhow::Result<O> {
1032 match self {
1033 ConnectionResult::Timeout => anyhow::bail!("Request timed out"),
1034 ConnectionResult::ConnectionReset => anyhow::bail!("Server reset the connection"),
1035 ConnectionResult::Result(r) => r,
1036 }
1037 }
1038}
1039
1040impl<O> From<anyhow::Result<O>> for ConnectionResult<O> {
1041 fn from(result: anyhow::Result<O>) -> Self {
1042 ConnectionResult::Result(result)
1043 }
1044}
1045
1046#[cfg(test)]
1047mod tests {
1048 use super::*;
1049
1050 #[test]
1051 fn test_fs_embed_iter_and_get() {
1052 let inherent_names: Vec<_> = FsEmbedTestAssets::iter().collect();
1053 assert!(
1054 inherent_names.iter().any(|name| name == "util.rs"),
1055 "iter should list files matching the include globs, got {inherent_names:?}"
1056 );
1057 assert!(
1058 !inherent_names.iter().any(|name| name.ends_with(".toml")),
1059 "iter should filter files excluded by the globs, got {inherent_names:?}"
1060 );
1061
1062 let trait_names: Vec<_> =
1063 <FsEmbedTestAssets as crate::__rust_embed::RustEmbed>::iter().collect();
1064 assert_eq!(inherent_names, trait_names);
1065
1066 let file = FsEmbedTestAssets::get("util.rs").expect("util.rs should be readable");
1067 assert!(
1068 std::str::from_utf8(&file.data)
1069 .expect("util.rs should be utf-8")
1070 .contains("fs_embed"),
1071 "get should read the real file contents"
1072 );
1073 assert!(
1074 FsEmbedTestAssets::get("Cargo.toml").is_none(),
1075 "get should filter files excluded by the globs"
1076 );
1077 }
1078
1079 #[cfg(not(feature = "debug-embed"))]
1080 crate::fs_embed! {
1081 struct FsEmbedTestAssets,
1082 crate_relative = "src",
1083 root_relative = "crates/util/src",
1084 include = ["*.rs"],
1085 exclude = ["test/**/*"],
1086 }
1087
1088 #[cfg(feature = "debug-embed")]
1091 crate::fs_embed! {
1092 struct FsEmbedTestAssets,
1093 crate_relative = "src",
1094 root_relative = "this-path-must-not-be-read",
1095 include = ["*.rs"],
1096 exclude = ["test/**/*"],
1097 }
1098
1099 #[test]
1100 fn test_parse_os_release() {
1101 let os_release =
1102 "NAME=\"Ubuntu\"\nID=ubuntu\nVERSION_ID=\"24.04\"\nPRETTY_NAME=\"Ubuntu 24.04 LTS\"\n";
1103 assert_eq!(
1104 parse_os_release(os_release),
1105 Some("ubuntu 24.04".to_string())
1106 );
1107
1108 assert_eq!(parse_os_release("ID=arch\n"), Some("arch".to_string()));
1110
1111 assert_eq!(parse_os_release("VERSION_ID=1\n"), None);
1113 assert_eq!(parse_os_release(""), None);
1114 }
1115
1116 #[test]
1117 fn test_extend_sorted() {
1118 let mut vec = vec![];
1119
1120 extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
1121 assert_eq!(vec, &[21, 17, 13, 8, 1]);
1122
1123 extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
1124 assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
1125
1126 extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
1127 assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
1128 }
1129
1130 #[test]
1131 fn test_truncate_to_bottom_n_sorted_by() {
1132 let mut vec: Vec<u32> = vec![5, 2, 3, 4, 1];
1133 truncate_to_bottom_n_sorted_by(&mut vec, 10, &u32::cmp);
1134 assert_eq!(vec, &[1, 2, 3, 4, 5]);
1135
1136 vec = vec![5, 2, 3, 4, 1];
1137 truncate_to_bottom_n_sorted_by(&mut vec, 5, &u32::cmp);
1138 assert_eq!(vec, &[1, 2, 3, 4, 5]);
1139
1140 vec = vec![5, 2, 3, 4, 1];
1141 truncate_to_bottom_n_sorted_by(&mut vec, 4, &u32::cmp);
1142 assert_eq!(vec, &[1, 2, 3, 4]);
1143
1144 vec = vec![5, 2, 3, 4, 1];
1145 truncate_to_bottom_n_sorted_by(&mut vec, 1, &u32::cmp);
1146 assert_eq!(vec, &[1]);
1147
1148 vec = vec![5, 2, 3, 4, 1];
1149 truncate_to_bottom_n_sorted_by(&mut vec, 0, &u32::cmp);
1150 assert!(vec.is_empty());
1151 }
1152
1153 #[test]
1154 fn test_iife() {
1155 fn option_returning_function() -> Option<()> {
1156 None
1157 }
1158
1159 let foo = maybe!({
1160 option_returning_function()?;
1161 Some(())
1162 });
1163
1164 assert_eq!(foo, None);
1165 }
1166
1167 #[test]
1168 fn test_truncate_and_trailoff() {
1169 assert_eq!(truncate_and_trailoff("", 5), "");
1170 assert_eq!(truncate_and_trailoff("aaaaaa", 7), "aaaaaa");
1171 assert_eq!(truncate_and_trailoff("aaaaaa", 6), "aaaaaa");
1172 assert_eq!(truncate_and_trailoff("aaaaaa", 5), "aaaaa…");
1173 assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
1174 assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
1175 assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèè…");
1176 }
1177
1178 #[test]
1179 fn test_truncate_and_remove_front() {
1180 assert_eq!(truncate_and_remove_front("", 5), "");
1181 assert_eq!(truncate_and_remove_front("aaaaaa", 7), "aaaaaa");
1182 assert_eq!(truncate_and_remove_front("aaaaaa", 6), "aaaaaa");
1183 assert_eq!(truncate_and_remove_front("aaaaaa", 5), "…aaaaa");
1184 assert_eq!(truncate_and_remove_front("èèèèèè", 7), "èèèèèè");
1185 assert_eq!(truncate_and_remove_front("èèèèèè", 6), "èèèèèè");
1186 assert_eq!(truncate_and_remove_front("èèèèèè", 5), "…èèèèè");
1187 }
1188
1189 #[test]
1190 fn test_numeric_prefix_str_method() {
1191 let target = "1a";
1192 assert_eq!(
1193 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1194 NumericPrefixWithSuffix(Some(1), "a")
1195 );
1196
1197 let target = "12ab";
1198 assert_eq!(
1199 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1200 NumericPrefixWithSuffix(Some(12), "ab")
1201 );
1202
1203 let target = "12_ab";
1204 assert_eq!(
1205 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1206 NumericPrefixWithSuffix(Some(12), "_ab")
1207 );
1208
1209 let target = "1_2ab";
1210 assert_eq!(
1211 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1212 NumericPrefixWithSuffix(Some(1), "_2ab")
1213 );
1214
1215 let target = "1.2";
1216 assert_eq!(
1217 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1218 NumericPrefixWithSuffix(Some(1), ".2")
1219 );
1220
1221 let target = "1.2_a";
1222 assert_eq!(
1223 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1224 NumericPrefixWithSuffix(Some(1), ".2_a")
1225 );
1226
1227 let target = "12.2_a";
1228 assert_eq!(
1229 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1230 NumericPrefixWithSuffix(Some(12), ".2_a")
1231 );
1232
1233 let target = "12a.2_a";
1234 assert_eq!(
1235 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1236 NumericPrefixWithSuffix(Some(12), "a.2_a")
1237 );
1238 }
1239
1240 #[test]
1241 fn test_numeric_prefix_with_suffix() {
1242 let mut sorted = vec!["1-abc", "10", "11def", "2", "21-abc"];
1243 sorted.sort_by_key(|s| NumericPrefixWithSuffix::from_numeric_prefixed_str(s));
1244 assert_eq!(sorted, ["1-abc", "2", "10", "11def", "21-abc"]);
1245
1246 for numeric_prefix_less in ["numeric_prefix_less", "aaa", "~™£"] {
1247 assert_eq!(
1248 NumericPrefixWithSuffix::from_numeric_prefixed_str(numeric_prefix_less),
1249 NumericPrefixWithSuffix(None, numeric_prefix_less),
1250 "String without numeric prefix `{numeric_prefix_less}` should not be converted into NumericPrefixWithSuffix"
1251 )
1252 }
1253 }
1254
1255 #[test]
1256 fn test_word_consists_of_emojis() {
1257 let words_to_test = vec![
1258 ("👨👩👧👧👋🥒", true),
1259 ("👋", true),
1260 ("!👋", false),
1261 ("👋!", false),
1262 ("👋 ", false),
1263 (" 👋", false),
1264 ("Test", false),
1265 ];
1266
1267 for (text, expected_result) in words_to_test {
1268 assert_eq!(word_consists_of_emojis(text), expected_result);
1269 }
1270 }
1271
1272 #[test]
1273 fn test_truncate_lines_and_trailoff() {
1274 let text = r#"Line 1
1275Line 2
1276Line 3"#;
1277
1278 assert_eq!(
1279 truncate_lines_and_trailoff(text, 2),
1280 r#"Line 1
1281…"#
1282 );
1283
1284 assert_eq!(
1285 truncate_lines_and_trailoff(text, 3),
1286 r#"Line 1
1287Line 2
1288…"#
1289 );
1290
1291 assert_eq!(
1292 truncate_lines_and_trailoff(text, 4),
1293 r#"Line 1
1294Line 2
1295Line 3"#
1296 );
1297 }
1298
1299 #[test]
1300 fn test_expanded_and_wrapped_usize_range() {
1301 assert_eq!(
1303 expanded_and_wrapped_usize_range(2..4, 1, 1, 8).collect::<Vec<usize>>(),
1304 (1..5).collect::<Vec<usize>>()
1305 );
1306 assert_eq!(
1308 expanded_and_wrapped_usize_range(2..4, 3, 1, 8).collect::<Vec<usize>>(),
1309 ((0..5).chain(7..8)).collect::<Vec<usize>>()
1310 );
1311 assert_eq!(
1313 expanded_and_wrapped_usize_range(2..4, 5, 1, 8).collect::<Vec<usize>>(),
1314 (0..8).collect::<Vec<usize>>()
1315 );
1316 assert_eq!(
1318 expanded_and_wrapped_usize_range(2..4, 10, 1, 8).collect::<Vec<usize>>(),
1319 (0..8).collect::<Vec<usize>>()
1320 );
1321 assert_eq!(
1323 expanded_and_wrapped_usize_range(3..5, 1, 4, 8).collect::<Vec<usize>>(),
1324 (0..1).chain(2..8).collect::<Vec<usize>>()
1325 );
1326 assert_eq!(
1328 expanded_and_wrapped_usize_range(3..5, 1, 5, 8).collect::<Vec<usize>>(),
1329 (0..8).collect::<Vec<usize>>()
1330 );
1331 assert_eq!(
1333 expanded_and_wrapped_usize_range(3..5, 1, 10, 8).collect::<Vec<usize>>(),
1334 (0..8).collect::<Vec<usize>>()
1335 );
1336 assert_eq!(
1338 expanded_and_wrapped_usize_range(3..5, 4, 4, 8).collect::<Vec<usize>>(),
1339 (0..8).collect::<Vec<usize>>()
1340 );
1341 }
1342
1343 #[test]
1344 fn test_wrapped_usize_outward_from() {
1345 assert_eq!(
1347 wrapped_usize_outward_from(4, 2, 2, 10).collect::<Vec<usize>>(),
1348 vec![4, 5, 3, 6, 2]
1349 );
1350 assert_eq!(
1352 wrapped_usize_outward_from(8, 2, 3, 10).collect::<Vec<usize>>(),
1353 vec![8, 9, 7, 0, 6, 1]
1354 );
1355 assert_eq!(
1357 wrapped_usize_outward_from(1, 3, 2, 10).collect::<Vec<usize>>(),
1358 vec![1, 2, 0, 3, 9, 8]
1359 );
1360 assert_eq!(
1362 wrapped_usize_outward_from(5, 10, 10, 8).collect::<Vec<usize>>(),
1363 vec![5, 6, 4, 7, 3, 0, 2, 1]
1364 );
1365 assert_eq!(
1367 wrapped_usize_outward_from(3, 0, 0, 8).collect::<Vec<usize>>(),
1368 vec![3]
1369 );
1370 assert_eq!(
1372 wrapped_usize_outward_from(15, 2, 2, 10).collect::<Vec<usize>>(),
1373 vec![5, 6, 4, 7, 3]
1374 );
1375 assert_eq!(
1377 wrapped_usize_outward_from(4, 2, 2, 0).collect::<Vec<usize>>(),
1378 Vec::<usize>::new()
1379 );
1380 }
1381
1382 #[test]
1383 fn test_split_with_ranges() {
1384 let input = "hi";
1385 let result = split_str_with_ranges(input, &|c| c == ' ');
1386
1387 assert_eq!(result.len(), 1);
1388 assert_eq!(result[0], (0..2, "hi"));
1389
1390 let input = "héllo🦀world";
1391 let result = split_str_with_ranges(input, &|c| c == '🦀');
1392
1393 assert_eq!(result.len(), 2);
1394 assert_eq!(result[0], (0..6, "héllo")); assert_eq!(result[1], (10..15, "world")); }
1397
1398 #[test]
1399 fn test_merge_json_values() {
1400 use serde_json::json;
1401
1402 let mut target = json!({
1403 "unchanged": 1,
1404 "replaced_scalar": "old",
1405 "replaced_array": ["default-1", "default-2"],
1406 "nulled": true,
1407 "array_becomes_object": [1, 2],
1408 "object_becomes_scalar": { "x": 1 },
1409 "nested": {
1410 "kept": true,
1411 "overridden": 2,
1412 "args": ["--default"],
1413 "deeper": { "list": [1, 2], "other": "kept" },
1414 },
1415 });
1416 let source = json!({
1417 "replaced_scalar": "new",
1418 "replaced_array": ["default-2", "user"],
1419 "nulled": null,
1420 "array_becomes_object": { "y": 2 },
1421 "object_becomes_scalar": 3,
1422 "inserted": ["brand-new"],
1423 "nested": {
1424 "overridden": 20,
1425 "args": ["--user"],
1426 "deeper": { "list": [3] },
1427 "inserted": { "z": true },
1428 },
1429 });
1430
1431 merge_json_value_into(source, &mut target);
1432
1433 assert_eq!(
1434 target,
1435 json!({
1436 "unchanged": 1,
1437 "replaced_scalar": "new",
1438 "replaced_array": ["default-2", "user"],
1439 "nulled": null,
1440 "array_becomes_object": { "y": 2 },
1441 "object_becomes_scalar": 3,
1442 "inserted": ["brand-new"],
1443 "nested": {
1444 "kept": true,
1445 "overridden": 20,
1446 "args": ["--user"],
1447 "deeper": { "list": [3], "other": "kept" },
1448 "inserted": { "z": true },
1449 },
1450 })
1451 );
1452 }
1453
1454 #[test]
1455 fn test_union_json_values() {
1456 use serde_json::json;
1457
1458 let mut target = json!({
1459 "unchanged": 1,
1460 "replaced_scalar": "old",
1461 "unioned_array": ["shared", "first"],
1462 "nested": {
1463 "kept": true,
1464 "plugins": [{ "name": "first-plugin" }],
1465 "scalar": 2,
1466 },
1467 });
1468 let source = json!({
1469 "replaced_scalar": "new",
1470 "unioned_array": ["shared", "second"],
1471 "inserted": ["brand-new"],
1472 "nested": {
1473 "plugins": [{ "name": "second-plugin" }],
1474 "scalar": 20,
1475 },
1476 });
1477
1478 union_json_value_into(source, &mut target);
1479
1480 assert_eq!(
1481 target,
1482 json!({
1483 "unchanged": 1,
1484 "replaced_scalar": "new",
1485 "unioned_array": ["shared", "first", "second"],
1486 "inserted": ["brand-new"],
1487 "nested": {
1488 "kept": true,
1489 "plugins": [{ "name": "first-plugin" }, { "name": "second-plugin" }],
1490 "scalar": 20,
1491 },
1492 })
1493 );
1494 }
1495}