Skip to main content

util/
util.rs

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    // This is bit magic equivalent to: b < 128 || b >= 192
60    (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
70/// Parses the contents of an `os-release` file (as found at `/etc/os-release`
71/// and described by the systemd spec) into a human-readable string such as
72/// `"ubuntu 24.04"`, combining the `ID` and `VERSION_ID` fields.
73///
74/// Returns `None` if no `ID` field is present. When `VERSION_ID` is absent
75/// (e.g. on rolling releases), only the `ID` is returned.
76pub 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
93/// Removes characters from the end of the string if its length is greater than `max_chars` and
94/// appends "..." to the string. Returns string unchanged if its length is smaller than max_chars.
95pub fn truncate_and_trailoff(s: &str, max_chars: usize) -> String {
96    debug_assert!(max_chars >= 5);
97
98    // If the string's byte length is <= max_chars, walking the string can be skipped since the
99    // number of chars is <= the number of bytes.
100    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
110/// Removes characters from the front of the string if its length is greater than `max_chars` and
111/// prepends the string with "...". Returns string unchanged if its length is smaller than max_chars.
112pub fn truncate_and_remove_front(s: &str, max_chars: usize) -> String {
113    debug_assert!(max_chars >= 5);
114
115    // If the string's byte length is <= max_chars, walking the string can be skipped since the
116    // number of chars is <= the number of bytes.
117    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
131/// Takes only `max_lines` from the string and, if there were more than `max_lines-1`, appends a
132/// a newline and "..." to the string, so that `max_lines` are returned.
133/// Returns string unchanged if its length is smaller than max_lines.
134pub 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
144/// Truncates the string at a character boundary, such that the result is less than `max_bytes` in
145/// length.
146pub 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
160/// Takes a prefix of complete lines which fit within the byte limit. If the first line is longer
161/// than the limit, truncates at a character boundary.
162pub 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            // Since the i-th character is \n, valid to slice at i + 1.
170            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    // Limit that includes all lines
182    assert_eq!(truncate_lines_to_byte_limit(text, 100), text);
183
184    // Exactly the first line
185    assert_eq!(truncate_lines_to_byte_limit(text, 7), "Line 1\n");
186
187    // Limit between lines
188    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    // Limit before first newline
192    assert_eq!(truncate_lines_to_byte_limit(text, 6), "Line ");
193
194    // Test with non-ASCII characters
195    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
202/// Extend a sorted vector with a sorted sequence of items, maintaining the vector's sort order and
203/// enforcing a maximum length. This also de-duplicates items. Sort the items according to the given callback. Before calling this,
204/// both `vec` and `new_items` should already be sorted according to the `cmp` comparator.
205pub 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/// Prevents execution of the application with root privileges on Unix systems.
226///
227/// This function checks if the current process is running with root privileges
228/// and terminates the program with an error message unless explicitly allowed via the
229/// `ZED_ALLOW_ROOT` environment variable.
230#[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/// Raises the soft limit on open file descriptors without changing the hard limit.
248///
249/// Call during startup, before spawning children that will inherit the limit.
250#[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    // These are startup targets, not OS ceilings. Preserve higher inherited limits.
257    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        // Some systems enforce a ceiling below the reported hard limit.
271        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    // SAFETY: If `getpwuid_r` doesn't error, we have the entry here.
304    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/// Returns a shell escaped path for the current zed executable
336#[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        // Might have been deleted during update; let's use the new binary if there is one.
351        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
359/// Returns a path for the zed cli executable, this function
360/// should be called from the zed executable, not zed-cli.
361pub 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        // On macOS, the zed executable and zed-cli are inside the app bundle,
371        // so here ./cli is for both installed and development builds.
372        &["./cli"]
373    } else if cfg!(target_os = "windows") {
374        // bin/zed.exe is for installed builds, ./cli.exe is for development builds.
375        &["bin/zed.exe", "./cli.exe"]
376    } else if cfg!(target_os = "linux") || cfg!(target_os = "freebsd") {
377        // bin is the standard, ./cli is for the target directory in development builds.
378        &["../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    // If possible, we want to `cd` in the user's `$HOME` to trigger programs
407    // such as direnv, asdf, mise, ... to adjust the PATH. These tools often hook
408    // into shell's `cd` command (and hooks) to manipulate env.
409    // We do this so that we get the env a user would have when spawning a shell
410    // in home directory.
411    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        // Skip SHLVL to prevent it from polluting Zed's process environment.
416        // The login shell used for env capture increments SHLVL, and if we propagate it,
417        // terminals spawned by Zed will inherit it and increment again, causing SHLVL
418        // to start at 2 instead of 1 (and increase by 2 on each reload).
419        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
434/// Configures the process to start a new session, to prevent interactive shells from taking control
435/// of the terminal.
436///
437/// For more details: <https://registerspill.thorstenball.com/p/how-to-lose-control-of-your-shell>
438pub fn set_pre_exec_to_start_new_session(
439    command: &mut std::process::Command,
440) -> &mut std::process::Command {
441    // safety: code in pre_exec should be signal safe.
442    // https://man7.org/linux/man-pages/man7/signal-safety.7.html
443    #[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
479/// Merges `source` into `target`: objects are merged recursively, key by key;
480/// any other colliding value in `target` — including arrays — is replaced by
481/// `source`'s value wholesale.
482pub 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
573/// Yields `[i, i + 1, i - 1, i + 2, ..]`, each modulo `wrap_length` and bounded by
574/// `additional_before` and `additional_after`. If the wrapping causes overlap, duplicates are not
575/// emitted. If wrap_length is 0, nothing is yielded.
576pub 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                // whitespace
647                0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.rng).copied(),
648                // two-byte greek letters
649                20..=32 => char::from_u32(self.rng.random_range(('α' as u32)..('ω' as u32 + 1))),
650                // // three-byte characters
651                33..=45 => ['✋', '✅', '❌', '❎', '⭐']
652                    .choose(&mut self.rng)
653                    .copied(),
654                // // four-byte characters
655                46..=58 => ['🍐', '🏀', '🍗', '🎉'].choose(&mut self.rng).copied(),
656                // ascii letters
657                _ => 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
665/// Get an embedded file as a string.
666pub 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
673/// The checkout that produced this binary, resolved at runtime by walking up to
674/// the first ancestor that contains a `.git` entry (a directory in a normal
675/// clone, a file in a git worktree or submodule). Cargo and corgi both place
676/// built binaries under `<repo>/target/<profile>/`, so the repository root is
677/// always an ancestor of the executable.
678///
679/// Dev-only affordances use this instead of baking a build-time path into the
680/// artifact: such a path points at the wrong checkout from any other worktree
681/// and, under corgi, is rejected because artifacts must be checkout-independent
682/// to be shared across worktrees.
683///
684/// The executable's launch path is tried first, then its canonical form, then
685/// the working directory. In CI, `target/` (or the checkout root) can be a
686/// symlink onto another volume, so canonicalizing the executable alone can walk
687/// off the checkout and miss `.git`; the launch path and the test runner's cwd
688/// (a crate dir under the checkout) stay inside it.
689pub 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/// Re-exports that back [`fs_embed!`] so a caller only needs to depend on `util`,
712/// not on `rust_embed` directly (the macro's dependency is an implementation
713/// detail). Hidden from the public API.
714#[doc(hidden)]
715pub mod __rust_embed {
716    pub use rust_embed::{EmbeddedFile, Filenames, Metadata, RustEmbed, utils};
717}
718
719/// Backs the dev arm of [`fs_embed!`]'s `iter`: every file under the root-relative
720/// directory that passes the same rust_embed include/exclude globs the
721/// release derive uses, so the dev and release file sets are identical. Reuses
722/// rust_embed's own matcher rather than reimplementing glob semantics.
723#[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/// Backs the dev arm of [`fs_embed!`]'s `get`: reads a single file from the
747/// checkout, returning `None` when the include/exclude globs filter it out so
748/// `get` matches release's embedded set exactly.
749#[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        // `crate_path` points the derive's generated code at util's re-export so
801        // the caller needs no direct `rust_embed` dependency.
802        #[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        // Mirror the derive's public surface: inherent `get`/`iter` (callable
814        // without the trait in scope) plus the trait impl (for generic bounds
815        // like `util::asset_str` and `handlebars::register_embed_templates`), so
816        // the two arms are interchangeable at call sites.
817        #[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/// A `rust_embed` asset source that embeds files in release builds. Dev builds
863/// read from the checkout at runtime unless the `debug-embed` feature is enabled,
864/// in which case they embed the files too.
865///
866/// It expands to one of these arms:
867/// * Release (`not(debug_assertions)`): `#[derive(RustEmbed)]` embedding
868///   `crate_relative` at build time, with the given `include`/`exclude` globs.
869/// * Dev with `debug-embed`: the same compile-time embedding as release.
870/// * Dev without `debug-embed`: a runtime filesystem source rooted at
871///   `root_relative`; edits appear on the next launch without a rebuild.
872///
873/// Two paths are required because the arms resolve from different bases: the
874/// derive reads `crate_relative` relative to the crate's `Cargo.toml`, while the
875/// runtime dev arm resolves `root_relative` relative to the repository root via
876/// [`dev_repo_root`]. Baking the build-time path into that arm would point at the
877/// wrong checkout from another worktree and is rejected by corgi, whose sandbox
878/// requires checkout-independent output.
879///
880/// ```ignore
881/// util::fs_embed! {
882///     pub struct Assets,
883///     crate_relative = "../../assets",
884///     root_relative = "assets",
885///     include = ["fonts/**/*", "themes/**/*", "*.md"],
886///     exclude = ["themes/src/*", "*.DS_Store"],
887/// }
888/// ```
889#[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/// A way to sort strings with starting numbers numerically first, falling back to alphanumeric one,
940/// case-insensitive.
941///
942/// This is useful for turning regular alphanumerically sorted sequences as `1-abc, 10, 11-def, .., 2, 21-abc`
943/// into `1-abc, 2, 10, 11-def, .., 21-abc`
944#[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
957/// When dealing with equality, we need to consider the case of the strings to achieve strict equality
958/// to handle cases like "a" < "A" instead of "a" == "A".
959impl 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
988/// Returns true if the given string consists of emojis only.
989/// E.g. "👨‍👩‍👧‍👧👋" will return true, but "👋!" will return false.
990pub 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
1001/// Similar to `str::split`, but also provides byte-offset ranges of the results. Unlike
1002/// `str::split`, this is not generic on pattern types and does not return an `Iterator`.
1003pub 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    // A consuming workspace does not contain a git dependency's files at this
1096    // repository-relative path, so `debug-embed` must not consult it.
1097    #[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        // VERSION_ID may be absent (e.g. rolling releases like Arch).
1116        assert_eq!(parse_os_release("ID=arch\n"), Some("arch".to_string()));
1117
1118        // Without an ID there is nothing usable to report.
1119        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        // Neither wrap
1309        assert_eq!(
1310            expanded_and_wrapped_usize_range(2..4, 1, 1, 8).collect::<Vec<usize>>(),
1311            (1..5).collect::<Vec<usize>>()
1312        );
1313        // Start wraps
1314        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        // Start wraps all the way around
1319        assert_eq!(
1320            expanded_and_wrapped_usize_range(2..4, 5, 1, 8).collect::<Vec<usize>>(),
1321            (0..8).collect::<Vec<usize>>()
1322        );
1323        // Start wraps all the way around and past 0
1324        assert_eq!(
1325            expanded_and_wrapped_usize_range(2..4, 10, 1, 8).collect::<Vec<usize>>(),
1326            (0..8).collect::<Vec<usize>>()
1327        );
1328        // End wraps
1329        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        // End wraps all the way around
1334        assert_eq!(
1335            expanded_and_wrapped_usize_range(3..5, 1, 5, 8).collect::<Vec<usize>>(),
1336            (0..8).collect::<Vec<usize>>()
1337        );
1338        // End wraps all the way around and past the end
1339        assert_eq!(
1340            expanded_and_wrapped_usize_range(3..5, 1, 10, 8).collect::<Vec<usize>>(),
1341            (0..8).collect::<Vec<usize>>()
1342        );
1343        // Both start and end wrap
1344        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        // No wrapping
1353        assert_eq!(
1354            wrapped_usize_outward_from(4, 2, 2, 10).collect::<Vec<usize>>(),
1355            vec![4, 5, 3, 6, 2]
1356        );
1357        // Wrapping at end
1358        assert_eq!(
1359            wrapped_usize_outward_from(8, 2, 3, 10).collect::<Vec<usize>>(),
1360            vec![8, 9, 7, 0, 6, 1]
1361        );
1362        // Wrapping at start
1363        assert_eq!(
1364            wrapped_usize_outward_from(1, 3, 2, 10).collect::<Vec<usize>>(),
1365            vec![1, 2, 0, 3, 9, 8]
1366        );
1367        // All values wrap around
1368        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        // None before / after
1373        assert_eq!(
1374            wrapped_usize_outward_from(3, 0, 0, 8).collect::<Vec<usize>>(),
1375            vec![3]
1376        );
1377        // Starting point already wrapped
1378        assert_eq!(
1379            wrapped_usize_outward_from(15, 2, 2, 10).collect::<Vec<usize>>(),
1380            vec![5, 6, 4, 7, 3]
1381        );
1382        // wrap_length of 0
1383        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")); // 'é' is 2 bytes
1402        assert_eq!(result[1], (10..15, "world")); // '🦀' is 4 bytes
1403    }
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}