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