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
48#[cfg(any(test, feature = "test-support"))]
49pub use util_macros::{line_endings, path, uri};
50
51#[cfg(not(target_family = "wasm"))]
52pub use self::shell::{
53    get_default_system_shell, get_default_system_shell_preferring_bash, get_system_shell,
54};
55
56#[inline]
57pub const fn is_utf8_char_boundary(u8: u8) -> bool {
58    // This is bit magic equivalent to: b < 128 || b >= 192
59    (u8 as i8) >= -0x40
60}
61
62pub fn truncate(s: &str, max_chars: usize) -> &str {
63    match s.char_indices().nth(max_chars) {
64        None => s,
65        Some((idx, _)) => &s[..idx],
66    }
67}
68
69/// Parses the contents of an `os-release` file (as found at `/etc/os-release`
70/// and described by the systemd spec) into a human-readable string such as
71/// `"ubuntu 24.04"`, combining the `ID` and `VERSION_ID` fields.
72///
73/// Returns `None` if no `ID` field is present. When `VERSION_ID` is absent
74/// (e.g. on rolling releases), only the `ID` is returned.
75pub fn parse_os_release(content: &str) -> Option<String> {
76    let mut id = None;
77    let mut version_id = None;
78    for line in content.lines() {
79        match line.split_once('=') {
80            Some(("ID", value)) => id = Some(value.trim_matches('"')),
81            Some(("VERSION_ID", value)) => version_id = Some(value.trim_matches('"')),
82            _ => {}
83        }
84    }
85    let id = id?;
86    Some(match version_id {
87        Some(version) => format!("{id} {version}"),
88        None => id.to_string(),
89    })
90}
91
92/// Removes characters from the end of the string if its length is greater than `max_chars` and
93/// appends "..." to the string. Returns string unchanged if its length is smaller than max_chars.
94pub fn truncate_and_trailoff(s: &str, max_chars: usize) -> String {
95    debug_assert!(max_chars >= 5);
96
97    // If the string's byte length is <= max_chars, walking the string can be skipped since the
98    // number of chars is <= the number of bytes.
99    if s.len() <= max_chars {
100        return s.to_string();
101    }
102    let truncation_ix = s.char_indices().map(|(i, _)| i).nth(max_chars);
103    match truncation_ix {
104        Some(index) => s[..index].to_string() + "…",
105        _ => s.to_string(),
106    }
107}
108
109/// Removes characters from the front of the string if its length is greater than `max_chars` and
110/// prepends the string with "...". Returns string unchanged if its length is smaller than max_chars.
111pub fn truncate_and_remove_front(s: &str, max_chars: usize) -> String {
112    debug_assert!(max_chars >= 5);
113
114    // If the string's byte length is <= max_chars, walking the string can be skipped since the
115    // number of chars is <= the number of bytes.
116    if s.len() <= max_chars {
117        return s.to_string();
118    }
119    let suffix_char_length = max_chars.saturating_sub(1);
120    let truncation_ix = s
121        .char_indices()
122        .map(|(i, _)| i)
123        .nth_back(suffix_char_length);
124    match truncation_ix {
125        Some(index) if index > 0 => "…".to_string() + &s[index..],
126        _ => s.to_string(),
127    }
128}
129
130/// Takes only `max_lines` from the string and, if there were more than `max_lines-1`, appends a
131/// a newline and "..." to the string, so that `max_lines` are returned.
132/// Returns string unchanged if its length is smaller than max_lines.
133pub fn truncate_lines_and_trailoff(s: &str, max_lines: usize) -> String {
134    let mut lines = s.lines().take(max_lines).collect::<Vec<_>>();
135    if lines.len() > max_lines - 1 {
136        lines.pop();
137        lines.join("\n") + "\n…"
138    } else {
139        lines.join("\n")
140    }
141}
142
143/// Truncates the string at a character boundary, such that the result is less than `max_bytes` in
144/// length.
145pub fn truncate_to_byte_limit(s: &str, max_bytes: usize) -> &str {
146    if s.len() < max_bytes {
147        return s;
148    }
149
150    for i in (0..max_bytes).rev() {
151        if s.is_char_boundary(i) {
152            return &s[..i];
153        }
154    }
155
156    ""
157}
158
159/// Takes a prefix of complete lines which fit within the byte limit. If the first line is longer
160/// than the limit, truncates at a character boundary.
161pub fn truncate_lines_to_byte_limit(s: &str, max_bytes: usize) -> &str {
162    if s.len() < max_bytes {
163        return s;
164    }
165
166    for i in (0..max_bytes).rev() {
167        if s.is_char_boundary(i) && s.as_bytes()[i] == b'\n' {
168            // Since the i-th character is \n, valid to slice at i + 1.
169            return &s[..i + 1];
170        }
171    }
172
173    truncate_to_byte_limit(s, max_bytes)
174}
175
176#[test]
177fn test_truncate_lines_to_byte_limit() {
178    let text = "Line 1\nLine 2\nLine 3\nLine 4";
179
180    // Limit that includes all lines
181    assert_eq!(truncate_lines_to_byte_limit(text, 100), text);
182
183    // Exactly the first line
184    assert_eq!(truncate_lines_to_byte_limit(text, 7), "Line 1\n");
185
186    // Limit between lines
187    assert_eq!(truncate_lines_to_byte_limit(text, 13), "Line 1\n");
188    assert_eq!(truncate_lines_to_byte_limit(text, 20), "Line 1\nLine 2\n");
189
190    // Limit before first newline
191    assert_eq!(truncate_lines_to_byte_limit(text, 6), "Line ");
192
193    // Test with non-ASCII characters
194    let text_utf8 = "Line 1\nLíne 2\nLine 3";
195    assert_eq!(
196        truncate_lines_to_byte_limit(text_utf8, 15),
197        "Line 1\nLíne 2\n"
198    );
199}
200
201/// Extend a sorted vector with a sorted sequence of items, maintaining the vector's sort order and
202/// enforcing a maximum length. This also de-duplicates items. Sort the items according to the given callback. Before calling this,
203/// both `vec` and `new_items` should already be sorted according to the `cmp` comparator.
204pub fn extend_sorted<T, I, F>(vec: &mut Vec<T>, new_items: I, limit: usize, mut cmp: F)
205where
206    I: IntoIterator<Item = T>,
207    F: FnMut(&T, &T) -> Ordering,
208{
209    let mut start_index = 0;
210    for new_item in new_items {
211        if let Err(i) = vec[start_index..].binary_search_by(|m| cmp(m, &new_item)) {
212            let index = start_index + i;
213            if vec.len() < limit {
214                vec.insert(index, new_item);
215            } else if index < vec.len() {
216                vec.pop();
217                vec.insert(index, new_item);
218            }
219            start_index = index;
220        }
221    }
222}
223
224/// Prevents execution of the application with root privileges on Unix systems.
225///
226/// This function checks if the current process is running with root privileges
227/// and terminates the program with an error message unless explicitly allowed via the
228/// `ZED_ALLOW_ROOT` environment variable.
229#[cfg(unix)]
230pub fn prevent_root_execution() {
231    let is_root = nix::unistd::geteuid().is_root();
232    let allow_root = std::env::var("ZED_ALLOW_ROOT").is_ok_and(|val| val == "true");
233
234    if is_root && !allow_root {
235        eprintln!(
236            "\
237Error: Running Zed as root or via sudo is unsupported.
238       Doing so (even once) may subtly break things for all subsequent non-root usage of Zed.
239       It is untested and not recommended, don't complain when things break.
240       If you wish to proceed anyways, set `ZED_ALLOW_ROOT=true` in your environment."
241        );
242        std::process::exit(1);
243    }
244}
245
246/// Raises the soft limit on open file descriptors without changing the hard limit.
247///
248/// Call during startup, before spawning children that will inherit the limit.
249#[cfg(unix)]
250pub fn increase_open_file_limit() -> Result<()> {
251    use anyhow::Context as _;
252    use nix::sys::resource::{Resource::RLIMIT_NOFILE, getrlimit, setrlimit};
253
254    let (soft_limit, hard_limit) = getrlimit(RLIMIT_NOFILE).context("getrlimit(RLIMIT_NOFILE)")?;
255    // These are startup targets, not OS ceilings. Preserve higher inherited limits.
256    let target = if cfg!(target_os = "macos") {
257        10_240
258    } else {
259        65_536
260    };
261    let mut requested_limit = hard_limit.min(target);
262
263    while requested_limit > soft_limit {
264        let Err(error) = setrlimit(RLIMIT_NOFILE, requested_limit, hard_limit) else {
265            log::info!("raised open file soft limit from {soft_limit} to {requested_limit}");
266            return Ok(());
267        };
268
269        // Some systems enforce a ceiling below the reported hard limit.
270        if error != nix::errno::Errno::EINVAL || requested_limit == soft_limit + 1 {
271            return Err(error).context("setrlimit(RLIMIT_NOFILE)");
272        }
273        requested_limit = soft_limit + (requested_limit - soft_limit) / 2;
274    }
275
276    Ok(())
277}
278
279#[cfg(unix)]
280fn load_shell_from_passwd() -> Result<()> {
281    let buflen = match unsafe { libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) } {
282        n if n < 0 => 1024,
283        n => n as usize,
284    };
285    let mut buffer = Vec::with_capacity(buflen);
286
287    let mut pwd: std::mem::MaybeUninit<libc::passwd> = std::mem::MaybeUninit::uninit();
288    let mut result: *mut libc::passwd = std::ptr::null_mut();
289
290    let uid = unsafe { libc::getuid() };
291    let status = unsafe {
292        libc::getpwuid_r(
293            uid,
294            pwd.as_mut_ptr(),
295            buffer.as_mut_ptr() as *mut libc::c_char,
296            buflen,
297            &mut result,
298        )
299    };
300    anyhow::ensure!(!result.is_null(), "passwd entry for uid {} not found", uid);
301
302    // SAFETY: If `getpwuid_r` doesn't error, we have the entry here.
303    let entry = unsafe { pwd.assume_init() };
304
305    anyhow::ensure!(
306        status == 0,
307        "call to getpwuid_r failed. uid: {}, status: {}",
308        uid,
309        status
310    );
311    anyhow::ensure!(
312        entry.pw_uid == uid,
313        "passwd entry has different uid ({}) than getuid ({}) returned",
314        entry.pw_uid,
315        uid,
316    );
317
318    let shell = unsafe { std::ffi::CStr::from_ptr(entry.pw_shell).to_str().unwrap() };
319    let should_set_shell = std::env::var("SHELL").map_or(true, |shell_env| {
320        shell_env != shell && !std::path::Path::new(&shell_env).exists()
321    });
322
323    if should_set_shell {
324        log::info!(
325            "updating SHELL environment variable to value from passwd entry: {:?}",
326            shell,
327        );
328        unsafe { std::env::set_var("SHELL", shell) };
329    }
330
331    Ok(())
332}
333
334/// Returns a shell escaped path for the current zed executable
335#[cfg(not(target_family = "wasm"))]
336pub fn get_shell_safe_zed_path(shell_kind: shell::ShellKind) -> anyhow::Result<String> {
337    use anyhow::Context as _;
338    use paths::PathExt;
339    let mut zed_path =
340        std::env::current_exe().context("Failed to determine current zed executable path.")?;
341    if cfg!(target_os = "linux")
342        && !zed_path.is_file()
343        && let Some(truncated) = zed_path
344            .clone()
345            .file_name()
346            .and_then(|s| s.to_str())
347            .and_then(|n| n.strip_suffix(" (deleted)"))
348    {
349        // Might have been deleted during update; let's use the new binary if there is one.
350        zed_path.set_file_name(truncated);
351    }
352
353    zed_path
354        .try_shell_safe(shell_kind)
355        .context("Failed to shell-escape Zed executable path.")
356}
357
358/// Returns a path for the zed cli executable, this function
359/// should be called from the zed executable, not zed-cli.
360pub fn get_zed_cli_path() -> Result<PathBuf> {
361    use anyhow::Context as _;
362    let zed_path =
363        std::env::current_exe().context("Failed to determine current zed executable path.")?;
364    let parent = zed_path
365        .parent()
366        .context("Failed to determine parent directory of zed executable path.")?;
367
368    let possible_locations: &[&str] = if cfg!(target_os = "macos") {
369        // On macOS, the zed executable and zed-cli are inside the app bundle,
370        // so here ./cli is for both installed and development builds.
371        &["./cli"]
372    } else if cfg!(target_os = "windows") {
373        // bin/zed.exe is for installed builds, ./cli.exe is for development builds.
374        &["bin/zed.exe", "./cli.exe"]
375    } else if cfg!(target_os = "linux") || cfg!(target_os = "freebsd") {
376        // bin is the standard, ./cli is for the target directory in development builds.
377        &["../bin/zed", "./cli"]
378    } else {
379        anyhow::bail!("unsupported platform for determining zed-cli path");
380    };
381
382    possible_locations
383        .iter()
384        .find_map(|p| {
385            parent
386                .join(p)
387                .canonicalize()
388                .ok()
389                .filter(|p| p != &zed_path)
390        })
391        .with_context(|| {
392            format!(
393                "could not find zed-cli from any of: {}",
394                possible_locations.join(", ")
395            )
396        })
397}
398
399#[cfg(unix)]
400pub async fn load_login_shell_environment() -> Result<()> {
401    use anyhow::Context as _;
402
403    load_shell_from_passwd().log_err();
404
405    // If possible, we want to `cd` in the user's `$HOME` to trigger programs
406    // such as direnv, asdf, mise, ... to adjust the PATH. These tools often hook
407    // into shell's `cd` command (and hooks) to manipulate env.
408    // We do this so that we get the env a user would have when spawning a shell
409    // in home directory.
410    for (name, value) in shell_env::capture(get_system_shell(), &[], paths::home_dir())
411        .await
412        .with_context(|| format!("capturing environment with {:?}", get_system_shell()))?
413    {
414        // Skip SHLVL to prevent it from polluting Zed's process environment.
415        // The login shell used for env capture increments SHLVL, and if we propagate it,
416        // terminals spawned by Zed will inherit it and increment again, causing SHLVL
417        // to start at 2 instead of 1 (and increase by 2 on each reload).
418        if name == "SHLVL" {
419            continue;
420        }
421        unsafe { std::env::set_var(&name, &value) };
422    }
423
424    log::info!(
425        "set environment variables from shell:{}, path:{}",
426        std::env::var("SHELL").unwrap_or_default(),
427        std::env::var("PATH").unwrap_or_default(),
428    );
429
430    Ok(())
431}
432
433/// Configures the process to start a new session, to prevent interactive shells from taking control
434/// of the terminal.
435///
436/// For more details: <https://registerspill.thorstenball.com/p/how-to-lose-control-of-your-shell>
437pub fn set_pre_exec_to_start_new_session(
438    command: &mut std::process::Command,
439) -> &mut std::process::Command {
440    // safety: code in pre_exec should be signal safe.
441    // https://man7.org/linux/man-pages/man7/signal-safety.7.html
442    #[cfg(unix)]
443    unsafe {
444        use std::os::unix::process::CommandExt;
445        command.pre_exec(|| {
446            libc::setsid();
447            Ok(())
448        });
449    };
450    command
451}
452
453pub fn merge_json_lenient_value_into(
454    source: serde_json_lenient::Value,
455    target: &mut serde_json_lenient::Value,
456) {
457    match (source, target) {
458        (serde_json_lenient::Value::Object(source), serde_json_lenient::Value::Object(target)) => {
459            for (key, value) in source {
460                if let Some(target) = target.get_mut(&key) {
461                    merge_json_lenient_value_into(value, target);
462                } else {
463                    target.insert(key, value);
464                }
465            }
466        }
467
468        (serde_json_lenient::Value::Array(source), serde_json_lenient::Value::Array(target)) => {
469            for value in source {
470                target.push(value);
471            }
472        }
473
474        (source, target) => *target = source,
475    }
476}
477
478/// Merges `source` into `target`: objects are merged recursively, key by key;
479/// any other colliding value in `target` — including arrays — is replaced by
480/// `source`'s value wholesale.
481pub fn merge_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
482    use serde_json::Value;
483
484    match (source, target) {
485        (Value::Object(source), Value::Object(target)) => {
486            for (key, value) in source {
487                if let Some(target) = target.get_mut(&key) {
488                    merge_json_value_into(value, target);
489                } else {
490                    target.insert(key, value);
491                }
492            }
493        }
494        (source, target) => *target = source,
495    }
496}
497
498pub fn union_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
499    use serde_json::Value;
500
501    match (source, target) {
502        (Value::Object(source), Value::Object(target)) => {
503            for (key, value) in source {
504                if let Some(target) = target.get_mut(&key) {
505                    union_json_value_into(value, target);
506                } else {
507                    target.insert(key, value);
508                }
509            }
510        }
511        (Value::Array(source), Value::Array(target)) => {
512            for value in source {
513                if !target.contains(&value) {
514                    target.push(value);
515                }
516            }
517        }
518        (source, target) => *target = source,
519    }
520}
521
522pub fn merge_non_null_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
523    use serde_json::Value;
524    if let Value::Object(source_object) = source {
525        let target_object = if let Value::Object(target) = target {
526            target
527        } else {
528            *target = Value::Object(Default::default());
529            target.as_object_mut().unwrap()
530        };
531        for (key, value) in source_object {
532            if let Some(target) = target_object.get_mut(&key) {
533                merge_non_null_json_value_into(value, target);
534            } else if !value.is_null() {
535                target_object.insert(key, value);
536            }
537        }
538    } else if !source.is_null() {
539        *target = source
540    }
541}
542
543pub fn expanded_and_wrapped_usize_range(
544    range: Range<usize>,
545    additional_before: usize,
546    additional_after: usize,
547    wrap_length: usize,
548) -> impl Iterator<Item = usize> {
549    let start_wraps = range.start < additional_before;
550    let end_wraps = wrap_length < range.end + additional_after;
551    if start_wraps && end_wraps {
552        Either::Left(0..wrap_length)
553    } else if start_wraps {
554        let wrapped_start = (range.start + wrap_length).saturating_sub(additional_before);
555        if wrapped_start <= range.end {
556            Either::Left(0..wrap_length)
557        } else {
558            Either::Right((0..range.end + additional_after).chain(wrapped_start..wrap_length))
559        }
560    } else if end_wraps {
561        let wrapped_end = range.end + additional_after - wrap_length;
562        if range.start <= wrapped_end {
563            Either::Left(0..wrap_length)
564        } else {
565            Either::Right((0..wrapped_end).chain(range.start - additional_before..wrap_length))
566        }
567    } else {
568        Either::Left((range.start - additional_before)..(range.end + additional_after))
569    }
570}
571
572/// Yields `[i, i + 1, i - 1, i + 2, ..]`, each modulo `wrap_length` and bounded by
573/// `additional_before` and `additional_after`. If the wrapping causes overlap, duplicates are not
574/// emitted. If wrap_length is 0, nothing is yielded.
575pub fn wrapped_usize_outward_from(
576    start: usize,
577    additional_before: usize,
578    additional_after: usize,
579    wrap_length: usize,
580) -> impl Iterator<Item = usize> {
581    let mut count = 0;
582    let mut after_offset = 1;
583    let mut before_offset = 1;
584
585    std::iter::from_fn(move || {
586        count += 1;
587        if count > wrap_length {
588            None
589        } else if count == 1 {
590            Some(start % wrap_length)
591        } else if after_offset <= additional_after && after_offset <= before_offset {
592            let value = (start + after_offset) % wrap_length;
593            after_offset += 1;
594            Some(value)
595        } else if before_offset <= additional_before {
596            let value = (start + wrap_length - before_offset) % wrap_length;
597            before_offset += 1;
598            Some(value)
599        } else if after_offset <= additional_after {
600            let value = (start + after_offset) % wrap_length;
601            after_offset += 1;
602            Some(value)
603        } else {
604            None
605        }
606    })
607}
608
609#[cfg(any(test, feature = "test-support"))]
610mod rng {
611    use rand::prelude::*;
612
613    pub struct RandomCharIter<T: Rng> {
614        rng: T,
615        simple_text: bool,
616    }
617
618    impl<T: Rng> RandomCharIter<T> {
619        pub fn new(rng: T) -> Self {
620            Self {
621                rng,
622                simple_text: std::env::var("SIMPLE_TEXT").is_ok_and(|v| !v.is_empty()),
623            }
624        }
625
626        pub fn with_simple_text(mut self) -> Self {
627            self.simple_text = true;
628            self
629        }
630    }
631
632    impl<T: Rng> Iterator for RandomCharIter<T> {
633        type Item = char;
634
635        fn next(&mut self) -> Option<Self::Item> {
636            if self.simple_text {
637                return if self.rng.random_range(0..100) < 5 {
638                    Some('\n')
639                } else {
640                    Some(self.rng.random_range(b'a'..b'z' + 1).into())
641                };
642            }
643
644            match self.rng.random_range(0..100) {
645                // whitespace
646                0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.rng).copied(),
647                // two-byte greek letters
648                20..=32 => char::from_u32(self.rng.random_range(('α' as u32)..('ω' as u32 + 1))),
649                // // three-byte characters
650                33..=45 => ['✋', '✅', '❌', '❎', '⭐']
651                    .choose(&mut self.rng)
652                    .copied(),
653                // // four-byte characters
654                46..=58 => ['🍐', '🏀', '🍗', '🎉'].choose(&mut self.rng).copied(),
655                // ascii letters
656                _ => Some(self.rng.random_range(b'a'..b'z' + 1).into()),
657            }
658        }
659    }
660}
661#[cfg(any(test, feature = "test-support"))]
662pub use rng::RandomCharIter;
663
664/// Get an embedded file as a string.
665pub fn asset_str<A: rust_embed::RustEmbed>(path: &str) -> Cow<'static, str> {
666    match A::get(path).expect(path).data {
667        Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()),
668        Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()),
669    }
670}
671
672/// The checkout that produced this binary, resolved at runtime by walking up to
673/// the first ancestor that contains a `.git` entry (a directory in a normal
674/// clone, a file in a git worktree or submodule). Cargo and corgi both place
675/// built binaries under `<repo>/target/<profile>/`, so the repository root is
676/// always an ancestor of the executable.
677///
678/// Dev-only affordances use this instead of baking a build-time path into the
679/// artifact: such a path points at the wrong checkout from any other worktree
680/// and, under corgi, is rejected because artifacts must be checkout-independent
681/// to be shared across worktrees.
682///
683/// The executable's launch path is tried first, then its canonical form, then
684/// the working directory. In CI, `target/` (or the checkout root) can be a
685/// symlink onto another volume, so canonicalizing the executable alone can walk
686/// off the checkout and miss `.git`; the launch path and the test runner's cwd
687/// (a crate dir under the checkout) stay inside it.
688pub fn dev_repo_root() -> Option<&'static std::path::Path> {
689    use std::path::PathBuf;
690    static ROOT: std::sync::OnceLock<Option<PathBuf>> = std::sync::OnceLock::new();
691    ROOT.get_or_init(|| {
692        let exe = std::env::current_exe().ok();
693        let candidates = [
694            exe.clone(),
695            exe.and_then(|exe| exe.canonicalize().ok()),
696            std::env::current_dir().ok(),
697        ];
698        candidates.into_iter().flatten().find_map(|start| {
699            Some(
700                start
701                    .ancestors()
702                    .find(|dir| dir.join(".git").exists())?
703                    .to_path_buf(),
704            )
705        })
706    })
707    .as_deref()
708}
709
710/// Re-exports that back [`fs_embed!`] so a caller only needs to depend on `util`,
711/// not on `rust_embed` directly (the macro's dependency is an implementation
712/// detail). Hidden from the public API.
713#[doc(hidden)]
714pub mod __rust_embed {
715    pub use rust_embed::{EmbeddedFile, Filenames, Metadata, RustEmbed, flate, utils};
716}
717
718/// Backs the dev arm of [`fs_embed!`]'s `iter`: every file under the root-relative
719/// directory that passes the same rust_embed include/exclude globs the
720/// release derive uses, so the dev and release file sets are identical. Reuses
721/// rust_embed's own matcher rather than reimplementing glob semantics.
722#[cfg(all(debug_assertions, not(feature = "debug-embed")))]
723#[doc(hidden)]
724pub fn __fs_embed_iter(
725    root_relative: &str,
726    includes: &[&str],
727    excludes: &[&str],
728) -> impl Iterator<Item = std::borrow::Cow<'static, str>> + 'static {
729    fs_embed_file_names(root_relative, includes, excludes)
730        .into_iter()
731        .map(std::borrow::Cow::Owned)
732}
733
734#[cfg(all(debug_assertions, not(feature = "debug-embed")))]
735fn fs_embed_file_names(root_relative: &str, includes: &[&str], excludes: &[&str]) -> Vec<String> {
736    let Some(root) = dev_repo_root().map(|root| root.join(root_relative)) else {
737        return Vec::new();
738    };
739    let matcher = rust_embed::utils::PathMatcher::new(includes, excludes);
740    rust_embed::utils::get_files(root.to_string_lossy().into_owned(), matcher)
741        .map(|entry| entry.rel_path)
742        .collect()
743}
744
745/// Backs the dev arm of [`fs_embed!`]'s `get`: reads a single file from the
746/// checkout, returning `None` when the include/exclude globs filter it out so
747/// `get` matches release's embedded set exactly.
748#[cfg(all(debug_assertions, not(feature = "debug-embed")))]
749#[doc(hidden)]
750pub fn __fs_embed_get(
751    root_relative: &str,
752    file_path: &str,
753    includes: &[&str],
754    excludes: &[&str],
755) -> Option<rust_embed::EmbeddedFile> {
756    let matcher = rust_embed::utils::PathMatcher::new(includes, excludes);
757    if !matcher.is_path_included(file_path) {
758        return None;
759    }
760    let root = dev_repo_root()
761        .expect("dev asset loading requires running from within the checkout")
762        .join(root_relative);
763    rust_embed::utils::read_file_from_fs(&root.join(file_path)).ok()
764}
765
766#[cfg(feature = "debug-embed")]
767#[doc(hidden)]
768#[macro_export]
769macro_rules! __fs_embed {
770    (
771        $vis:vis struct $name:ident,
772        crate_relative = $crate_relative:literal,
773        root_relative = $root_relative:literal
774        $(, include = [$($include:literal),* $(,)?])?
775        $(, exclude = [$($exclude:literal),* $(,)?])?
776        $(,)?
777    ) => {
778        #[derive($crate::__rust_embed::RustEmbed)]
779        #[crate_path = "::util::__rust_embed"]
780        #[folder = $crate_relative]
781        $($(#[include = $include])*)?
782        $($(#[exclude = $exclude])*)?
783        $vis struct $name;
784    };
785}
786
787#[cfg(not(feature = "debug-embed"))]
788#[doc(hidden)]
789#[macro_export]
790macro_rules! __fs_embed {
791    (
792        $vis:vis struct $name:ident,
793        crate_relative = $crate_relative:literal,
794        root_relative = $root_relative:literal
795        $(, include = [$($include:literal),* $(,)?])?
796        $(, exclude = [$($exclude:literal),* $(,)?])?
797        $(,)?
798    ) => {
799        // `crate_path` points the derive's generated code at util's re-export so
800        // the caller needs no direct `rust_embed` dependency.
801        #[cfg(not(debug_assertions))]
802        #[derive($crate::__rust_embed::RustEmbed)]
803        #[crate_path = "::util::__rust_embed"]
804        #[folder = $crate_relative]
805        $($(#[include = $include])*)?
806        $($(#[exclude = $exclude])*)?
807        $vis struct $name;
808
809        #[cfg(debug_assertions)]
810        $vis struct $name;
811
812        // Mirror the derive's public surface: inherent `get`/`iter` (callable
813        // without the trait in scope) plus the trait impl (for generic bounds
814        // like `util::asset_str` and `handlebars::register_embed_templates`), so
815        // the two arms are interchangeable at call sites.
816        #[cfg(debug_assertions)]
817        impl $name {
818            pub fn get(
819                file_path: &str,
820            ) -> ::core::option::Option<$crate::__rust_embed::EmbeddedFile> {
821                $crate::__fs_embed_get(
822                    $root_relative,
823                    file_path,
824                    &[$($($include),*)?],
825                    &[$($($exclude),*)?],
826                )
827            }
828
829            pub fn iter(
830            ) -> impl ::core::iter::Iterator<Item = ::std::borrow::Cow<'static, str>> + 'static
831            {
832                $crate::__fs_embed_iter(
833                    $root_relative,
834                    &[$($($include),*)?],
835                    &[$($($exclude),*)?],
836                )
837            }
838        }
839
840        #[cfg(debug_assertions)]
841        impl $crate::__rust_embed::RustEmbed for $name {
842            fn get(
843                file_path: &str,
844            ) -> ::core::option::Option<$crate::__rust_embed::EmbeddedFile> {
845                <$name>::get(file_path)
846            }
847
848            fn iter(
849            ) -> impl ::core::iter::Iterator<Item = ::std::borrow::Cow<'static, str>> + 'static
850            {
851                $crate::__fs_embed_iter(
852                    $root_relative,
853                    &[$($($include),*)?],
854                    &[$($($exclude),*)?],
855                )
856            }
857        }
858    };
859}
860
861/// A `rust_embed` asset source that embeds files in release builds. Dev builds
862/// read from the checkout at runtime unless the `debug-embed` feature is enabled,
863/// in which case they embed the files too.
864///
865/// It expands to one of these arms:
866/// * Release (`not(debug_assertions)`): `#[derive(RustEmbed)]` embedding
867///   `crate_relative` at build time, with the given `include`/`exclude` globs.
868/// * Dev with `debug-embed`: the same compile-time embedding as release.
869/// * Dev without `debug-embed`: a runtime filesystem source rooted at
870///   `root_relative`; edits appear on the next launch without a rebuild.
871///
872/// Two paths are required because the arms resolve from different bases: the
873/// derive reads `crate_relative` relative to the crate's `Cargo.toml`, while the
874/// runtime dev arm resolves `root_relative` relative to the repository root via
875/// [`dev_repo_root`]. Baking the build-time path into that arm would point at the
876/// wrong checkout from another worktree and is rejected by corgi, whose sandbox
877/// requires checkout-independent output.
878///
879/// ```ignore
880/// util::fs_embed! {
881///     pub struct Assets,
882///     crate_relative = "../../assets",
883///     root_relative = "assets",
884///     include = ["fonts/**/*", "themes/**/*", "*.md"],
885///     exclude = ["themes/src/*", "*.DS_Store"],
886/// }
887/// ```
888#[macro_export]
889macro_rules! fs_embed {
890    ($($tokens:tt)*) => {
891        $crate::__fs_embed!($($tokens)*);
892    };
893}
894
895pub trait RangeExt<T> {
896    fn sorted(&self) -> Self;
897    fn to_inclusive(&self) -> RangeInclusive<T>;
898    fn overlaps(&self, other: &Range<T>) -> bool;
899    fn contains_inclusive(&self, other: &Range<T>) -> bool;
900}
901
902impl<T: Ord + Clone> RangeExt<T> for Range<T> {
903    fn sorted(&self) -> Self {
904        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
905    }
906
907    fn to_inclusive(&self) -> RangeInclusive<T> {
908        self.start.clone()..=self.end.clone()
909    }
910
911    fn overlaps(&self, other: &Range<T>) -> bool {
912        self.start < other.end && other.start < self.end
913    }
914
915    fn contains_inclusive(&self, other: &Range<T>) -> bool {
916        self.start <= other.start && other.end <= self.end
917    }
918}
919
920impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
921    fn sorted(&self) -> Self {
922        cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
923    }
924
925    fn to_inclusive(&self) -> RangeInclusive<T> {
926        self.clone()
927    }
928
929    fn overlaps(&self, other: &Range<T>) -> bool {
930        self.start() < &other.end && &other.start <= self.end()
931    }
932
933    fn contains_inclusive(&self, other: &Range<T>) -> bool {
934        self.start() <= &other.start && &other.end <= self.end()
935    }
936}
937
938/// A way to sort strings with starting numbers numerically first, falling back to alphanumeric one,
939/// case-insensitive.
940///
941/// This is useful for turning regular alphanumerically sorted sequences as `1-abc, 10, 11-def, .., 2, 21-abc`
942/// into `1-abc, 2, 10, 11-def, .., 21-abc`
943#[derive(Debug, PartialEq, Eq)]
944pub struct NumericPrefixWithSuffix<'a>(Option<u64>, &'a str);
945
946impl<'a> NumericPrefixWithSuffix<'a> {
947    pub fn from_numeric_prefixed_str(str: &'a str) -> Self {
948        let i = str.chars().take_while(|c| c.is_ascii_digit()).count();
949        let (prefix, remainder) = str.split_at(i);
950
951        let prefix = prefix.parse().ok();
952        Self(prefix, remainder)
953    }
954}
955
956/// When dealing with equality, we need to consider the case of the strings to achieve strict equality
957/// to handle cases like "a" < "A" instead of "a" == "A".
958impl Ord for NumericPrefixWithSuffix<'_> {
959    fn cmp(&self, other: &Self) -> Ordering {
960        match (self.0, other.0) {
961            (None, None) => UniCase::new(self.1)
962                .cmp(&UniCase::new(other.1))
963                .then_with(|| self.1.cmp(other.1).reverse()),
964            (None, Some(_)) => Ordering::Greater,
965            (Some(_), None) => Ordering::Less,
966            (Some(a), Some(b)) => a.cmp(&b).then_with(|| {
967                UniCase::new(self.1)
968                    .cmp(&UniCase::new(other.1))
969                    .then_with(|| self.1.cmp(other.1).reverse())
970            }),
971        }
972    }
973}
974
975impl PartialOrd for NumericPrefixWithSuffix<'_> {
976    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
977        Some(self.cmp(other))
978    }
979}
980
981fn emoji_regex() -> &'static Regex {
982    static EMOJI_REGEX: LazyLock<Regex> =
983        LazyLock::new(|| Regex::new("(\\p{Emoji}|\u{200D})").unwrap());
984    &EMOJI_REGEX
985}
986
987/// Returns true if the given string consists of emojis only.
988/// E.g. "👨‍👩‍👧‍👧👋" will return true, but "👋!" will return false.
989pub fn word_consists_of_emojis(s: &str) -> bool {
990    let mut prev_end = 0;
991    for capture in emoji_regex().find_iter(s) {
992        if capture.start() != prev_end {
993            return false;
994        }
995        prev_end = capture.end();
996    }
997    prev_end == s.len()
998}
999
1000/// Similar to `str::split`, but also provides byte-offset ranges of the results. Unlike
1001/// `str::split`, this is not generic on pattern types and does not return an `Iterator`.
1002pub fn split_str_with_ranges<'s>(
1003    s: &'s str,
1004    pat: &dyn Fn(char) -> bool,
1005) -> Vec<(Range<usize>, &'s str)> {
1006    let mut result = Vec::new();
1007    let mut start = 0;
1008
1009    for (i, ch) in s.char_indices() {
1010        if pat(ch) {
1011            if i > start {
1012                result.push((start..i, &s[start..i]));
1013            }
1014            start = i + ch.len_utf8();
1015        }
1016    }
1017
1018    if s.len() > start {
1019        result.push((start..s.len(), &s[start..s.len()]));
1020    }
1021
1022    result
1023}
1024
1025pub fn default<D: Default>() -> D {
1026    Default::default()
1027}
1028
1029#[derive(Debug)]
1030pub enum ConnectionResult<O> {
1031    Timeout,
1032    ConnectionReset,
1033    Result(anyhow::Result<O>),
1034}
1035
1036impl<O> ConnectionResult<O> {
1037    pub fn into_response(self) -> anyhow::Result<O> {
1038        match self {
1039            ConnectionResult::Timeout => anyhow::bail!("Request timed out"),
1040            ConnectionResult::ConnectionReset => anyhow::bail!("Server reset the connection"),
1041            ConnectionResult::Result(r) => r,
1042        }
1043    }
1044}
1045
1046impl<O> From<anyhow::Result<O>> for ConnectionResult<O> {
1047    fn from(result: anyhow::Result<O>) -> Self {
1048        ConnectionResult::Result(result)
1049    }
1050}
1051
1052#[cfg(test)]
1053mod tests {
1054    use super::*;
1055
1056    #[test]
1057    fn test_fs_embed_iter_and_get() {
1058        let inherent_names: Vec<_> = FsEmbedTestAssets::iter().collect();
1059        assert!(
1060            inherent_names.iter().any(|name| name == "util.rs"),
1061            "iter should list files matching the include globs, got {inherent_names:?}"
1062        );
1063        assert!(
1064            !inherent_names.iter().any(|name| name.ends_with(".toml")),
1065            "iter should filter files excluded by the globs, got {inherent_names:?}"
1066        );
1067
1068        let trait_names: Vec<_> =
1069            <FsEmbedTestAssets as crate::__rust_embed::RustEmbed>::iter().collect();
1070        assert_eq!(inherent_names, trait_names);
1071
1072        let file = FsEmbedTestAssets::get("util.rs").expect("util.rs should be readable");
1073        assert!(
1074            std::str::from_utf8(&file.data)
1075                .expect("util.rs should be utf-8")
1076                .contains("fs_embed"),
1077            "get should read the real file contents"
1078        );
1079        assert!(
1080            FsEmbedTestAssets::get("Cargo.toml").is_none(),
1081            "get should filter files excluded by the globs"
1082        );
1083    }
1084
1085    #[cfg(not(feature = "debug-embed"))]
1086    crate::fs_embed! {
1087        struct FsEmbedTestAssets,
1088        crate_relative = "src",
1089        root_relative = "crates/util/src",
1090        include = ["*.rs"],
1091        exclude = ["test/**/*"],
1092    }
1093
1094    // A consuming workspace does not contain a git dependency's files at this
1095    // repository-relative path, so `debug-embed` must not consult it.
1096    #[cfg(feature = "debug-embed")]
1097    crate::fs_embed! {
1098        struct FsEmbedTestAssets,
1099        crate_relative = "src",
1100        root_relative = "this-path-must-not-be-read",
1101        include = ["*.rs"],
1102        exclude = ["test/**/*"],
1103    }
1104
1105    #[test]
1106    fn test_parse_os_release() {
1107        let os_release =
1108            "NAME=\"Ubuntu\"\nID=ubuntu\nVERSION_ID=\"24.04\"\nPRETTY_NAME=\"Ubuntu 24.04 LTS\"\n";
1109        assert_eq!(
1110            parse_os_release(os_release),
1111            Some("ubuntu 24.04".to_string())
1112        );
1113
1114        // VERSION_ID may be absent (e.g. rolling releases like Arch).
1115        assert_eq!(parse_os_release("ID=arch\n"), Some("arch".to_string()));
1116
1117        // Without an ID there is nothing usable to report.
1118        assert_eq!(parse_os_release("VERSION_ID=1\n"), None);
1119        assert_eq!(parse_os_release(""), None);
1120    }
1121
1122    #[test]
1123    fn test_extend_sorted() {
1124        let mut vec = vec![];
1125
1126        extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
1127        assert_eq!(vec, &[21, 17, 13, 8, 1]);
1128
1129        extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
1130        assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
1131
1132        extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
1133        assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
1134    }
1135
1136    #[test]
1137    fn test_truncate_to_bottom_n_sorted_by() {
1138        let mut vec: Vec<u32> = vec![5, 2, 3, 4, 1];
1139        truncate_to_bottom_n_sorted_by(&mut vec, 10, &u32::cmp);
1140        assert_eq!(vec, &[1, 2, 3, 4, 5]);
1141
1142        vec = vec![5, 2, 3, 4, 1];
1143        truncate_to_bottom_n_sorted_by(&mut vec, 5, &u32::cmp);
1144        assert_eq!(vec, &[1, 2, 3, 4, 5]);
1145
1146        vec = vec![5, 2, 3, 4, 1];
1147        truncate_to_bottom_n_sorted_by(&mut vec, 4, &u32::cmp);
1148        assert_eq!(vec, &[1, 2, 3, 4]);
1149
1150        vec = vec![5, 2, 3, 4, 1];
1151        truncate_to_bottom_n_sorted_by(&mut vec, 1, &u32::cmp);
1152        assert_eq!(vec, &[1]);
1153
1154        vec = vec![5, 2, 3, 4, 1];
1155        truncate_to_bottom_n_sorted_by(&mut vec, 0, &u32::cmp);
1156        assert!(vec.is_empty());
1157    }
1158
1159    #[test]
1160    fn test_iife() {
1161        fn option_returning_function() -> Option<()> {
1162            None
1163        }
1164
1165        let foo = maybe!({
1166            option_returning_function()?;
1167            Some(())
1168        });
1169
1170        assert_eq!(foo, None);
1171    }
1172
1173    #[test]
1174    fn test_truncate_and_trailoff() {
1175        assert_eq!(truncate_and_trailoff("", 5), "");
1176        assert_eq!(truncate_and_trailoff("aaaaaa", 7), "aaaaaa");
1177        assert_eq!(truncate_and_trailoff("aaaaaa", 6), "aaaaaa");
1178        assert_eq!(truncate_and_trailoff("aaaaaa", 5), "aaaaa…");
1179        assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
1180        assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
1181        assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèè…");
1182    }
1183
1184    #[test]
1185    fn test_truncate_and_remove_front() {
1186        assert_eq!(truncate_and_remove_front("", 5), "");
1187        assert_eq!(truncate_and_remove_front("aaaaaa", 7), "aaaaaa");
1188        assert_eq!(truncate_and_remove_front("aaaaaa", 6), "aaaaaa");
1189        assert_eq!(truncate_and_remove_front("aaaaaa", 5), "…aaaaa");
1190        assert_eq!(truncate_and_remove_front("èèèèèè", 7), "èèèèèè");
1191        assert_eq!(truncate_and_remove_front("èèèèèè", 6), "èèèèèè");
1192        assert_eq!(truncate_and_remove_front("èèèèèè", 5), "…èèèèè");
1193    }
1194
1195    #[test]
1196    fn test_numeric_prefix_str_method() {
1197        let target = "1a";
1198        assert_eq!(
1199            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1200            NumericPrefixWithSuffix(Some(1), "a")
1201        );
1202
1203        let target = "12ab";
1204        assert_eq!(
1205            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1206            NumericPrefixWithSuffix(Some(12), "ab")
1207        );
1208
1209        let target = "12_ab";
1210        assert_eq!(
1211            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1212            NumericPrefixWithSuffix(Some(12), "_ab")
1213        );
1214
1215        let target = "1_2ab";
1216        assert_eq!(
1217            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1218            NumericPrefixWithSuffix(Some(1), "_2ab")
1219        );
1220
1221        let target = "1.2";
1222        assert_eq!(
1223            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1224            NumericPrefixWithSuffix(Some(1), ".2")
1225        );
1226
1227        let target = "1.2_a";
1228        assert_eq!(
1229            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1230            NumericPrefixWithSuffix(Some(1), ".2_a")
1231        );
1232
1233        let target = "12.2_a";
1234        assert_eq!(
1235            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1236            NumericPrefixWithSuffix(Some(12), ".2_a")
1237        );
1238
1239        let target = "12a.2_a";
1240        assert_eq!(
1241            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
1242            NumericPrefixWithSuffix(Some(12), "a.2_a")
1243        );
1244    }
1245
1246    #[test]
1247    fn test_numeric_prefix_with_suffix() {
1248        let mut sorted = vec!["1-abc", "10", "11def", "2", "21-abc"];
1249        sorted.sort_by_key(|s| NumericPrefixWithSuffix::from_numeric_prefixed_str(s));
1250        assert_eq!(sorted, ["1-abc", "2", "10", "11def", "21-abc"]);
1251
1252        for numeric_prefix_less in ["numeric_prefix_less", "aaa", "~™£"] {
1253            assert_eq!(
1254                NumericPrefixWithSuffix::from_numeric_prefixed_str(numeric_prefix_less),
1255                NumericPrefixWithSuffix(None, numeric_prefix_less),
1256                "String without numeric prefix `{numeric_prefix_less}` should not be converted into NumericPrefixWithSuffix"
1257            )
1258        }
1259    }
1260
1261    #[test]
1262    fn test_word_consists_of_emojis() {
1263        let words_to_test = vec![
1264            ("👨‍👩‍👧‍👧👋🥒", true),
1265            ("👋", true),
1266            ("!👋", false),
1267            ("👋!", false),
1268            ("👋 ", false),
1269            (" 👋", false),
1270            ("Test", false),
1271        ];
1272
1273        for (text, expected_result) in words_to_test {
1274            assert_eq!(word_consists_of_emojis(text), expected_result);
1275        }
1276    }
1277
1278    #[test]
1279    fn test_truncate_lines_and_trailoff() {
1280        let text = r#"Line 1
1281Line 2
1282Line 3"#;
1283
1284        assert_eq!(
1285            truncate_lines_and_trailoff(text, 2),
1286            r#"Line 1
1287…"#
1288        );
1289
1290        assert_eq!(
1291            truncate_lines_and_trailoff(text, 3),
1292            r#"Line 1
1293Line 2
1294…"#
1295        );
1296
1297        assert_eq!(
1298            truncate_lines_and_trailoff(text, 4),
1299            r#"Line 1
1300Line 2
1301Line 3"#
1302        );
1303    }
1304
1305    #[test]
1306    fn test_expanded_and_wrapped_usize_range() {
1307        // Neither wrap
1308        assert_eq!(
1309            expanded_and_wrapped_usize_range(2..4, 1, 1, 8).collect::<Vec<usize>>(),
1310            (1..5).collect::<Vec<usize>>()
1311        );
1312        // Start wraps
1313        assert_eq!(
1314            expanded_and_wrapped_usize_range(2..4, 3, 1, 8).collect::<Vec<usize>>(),
1315            ((0..5).chain(7..8)).collect::<Vec<usize>>()
1316        );
1317        // Start wraps all the way around
1318        assert_eq!(
1319            expanded_and_wrapped_usize_range(2..4, 5, 1, 8).collect::<Vec<usize>>(),
1320            (0..8).collect::<Vec<usize>>()
1321        );
1322        // Start wraps all the way around and past 0
1323        assert_eq!(
1324            expanded_and_wrapped_usize_range(2..4, 10, 1, 8).collect::<Vec<usize>>(),
1325            (0..8).collect::<Vec<usize>>()
1326        );
1327        // End wraps
1328        assert_eq!(
1329            expanded_and_wrapped_usize_range(3..5, 1, 4, 8).collect::<Vec<usize>>(),
1330            (0..1).chain(2..8).collect::<Vec<usize>>()
1331        );
1332        // End wraps all the way around
1333        assert_eq!(
1334            expanded_and_wrapped_usize_range(3..5, 1, 5, 8).collect::<Vec<usize>>(),
1335            (0..8).collect::<Vec<usize>>()
1336        );
1337        // End wraps all the way around and past the end
1338        assert_eq!(
1339            expanded_and_wrapped_usize_range(3..5, 1, 10, 8).collect::<Vec<usize>>(),
1340            (0..8).collect::<Vec<usize>>()
1341        );
1342        // Both start and end wrap
1343        assert_eq!(
1344            expanded_and_wrapped_usize_range(3..5, 4, 4, 8).collect::<Vec<usize>>(),
1345            (0..8).collect::<Vec<usize>>()
1346        );
1347    }
1348
1349    #[test]
1350    fn test_wrapped_usize_outward_from() {
1351        // No wrapping
1352        assert_eq!(
1353            wrapped_usize_outward_from(4, 2, 2, 10).collect::<Vec<usize>>(),
1354            vec![4, 5, 3, 6, 2]
1355        );
1356        // Wrapping at end
1357        assert_eq!(
1358            wrapped_usize_outward_from(8, 2, 3, 10).collect::<Vec<usize>>(),
1359            vec![8, 9, 7, 0, 6, 1]
1360        );
1361        // Wrapping at start
1362        assert_eq!(
1363            wrapped_usize_outward_from(1, 3, 2, 10).collect::<Vec<usize>>(),
1364            vec![1, 2, 0, 3, 9, 8]
1365        );
1366        // All values wrap around
1367        assert_eq!(
1368            wrapped_usize_outward_from(5, 10, 10, 8).collect::<Vec<usize>>(),
1369            vec![5, 6, 4, 7, 3, 0, 2, 1]
1370        );
1371        // None before / after
1372        assert_eq!(
1373            wrapped_usize_outward_from(3, 0, 0, 8).collect::<Vec<usize>>(),
1374            vec![3]
1375        );
1376        // Starting point already wrapped
1377        assert_eq!(
1378            wrapped_usize_outward_from(15, 2, 2, 10).collect::<Vec<usize>>(),
1379            vec![5, 6, 4, 7, 3]
1380        );
1381        // wrap_length of 0
1382        assert_eq!(
1383            wrapped_usize_outward_from(4, 2, 2, 0).collect::<Vec<usize>>(),
1384            Vec::<usize>::new()
1385        );
1386    }
1387
1388    #[test]
1389    fn test_split_with_ranges() {
1390        let input = "hi";
1391        let result = split_str_with_ranges(input, &|c| c == ' ');
1392
1393        assert_eq!(result.len(), 1);
1394        assert_eq!(result[0], (0..2, "hi"));
1395
1396        let input = "héllo🦀world";
1397        let result = split_str_with_ranges(input, &|c| c == '🦀');
1398
1399        assert_eq!(result.len(), 2);
1400        assert_eq!(result[0], (0..6, "héllo")); // 'é' is 2 bytes
1401        assert_eq!(result[1], (10..15, "world")); // '🦀' is 4 bytes
1402    }
1403
1404    #[test]
1405    fn test_merge_json_values() {
1406        use serde_json::json;
1407
1408        let mut target = json!({
1409            "unchanged": 1,
1410            "replaced_scalar": "old",
1411            "replaced_array": ["default-1", "default-2"],
1412            "nulled": true,
1413            "array_becomes_object": [1, 2],
1414            "object_becomes_scalar": { "x": 1 },
1415            "nested": {
1416                "kept": true,
1417                "overridden": 2,
1418                "args": ["--default"],
1419                "deeper": { "list": [1, 2], "other": "kept" },
1420            },
1421        });
1422        let source = json!({
1423            "replaced_scalar": "new",
1424            "replaced_array": ["default-2", "user"],
1425            "nulled": null,
1426            "array_becomes_object": { "y": 2 },
1427            "object_becomes_scalar": 3,
1428            "inserted": ["brand-new"],
1429            "nested": {
1430                "overridden": 20,
1431                "args": ["--user"],
1432                "deeper": { "list": [3] },
1433                "inserted": { "z": true },
1434            },
1435        });
1436
1437        merge_json_value_into(source, &mut target);
1438
1439        assert_eq!(
1440            target,
1441            json!({
1442                "unchanged": 1,
1443                "replaced_scalar": "new",
1444                "replaced_array": ["default-2", "user"],
1445                "nulled": null,
1446                "array_becomes_object": { "y": 2 },
1447                "object_becomes_scalar": 3,
1448                "inserted": ["brand-new"],
1449                "nested": {
1450                    "kept": true,
1451                    "overridden": 20,
1452                    "args": ["--user"],
1453                    "deeper": { "list": [3], "other": "kept" },
1454                    "inserted": { "z": true },
1455                },
1456            })
1457        );
1458    }
1459
1460    #[test]
1461    fn test_union_json_values() {
1462        use serde_json::json;
1463
1464        let mut target = json!({
1465            "unchanged": 1,
1466            "replaced_scalar": "old",
1467            "unioned_array": ["shared", "first"],
1468            "nested": {
1469                "kept": true,
1470                "plugins": [{ "name": "first-plugin" }],
1471                "scalar": 2,
1472            },
1473        });
1474        let source = json!({
1475            "replaced_scalar": "new",
1476            "unioned_array": ["shared", "second"],
1477            "inserted": ["brand-new"],
1478            "nested": {
1479                "plugins": [{ "name": "second-plugin" }],
1480                "scalar": 20,
1481            },
1482        });
1483
1484        union_json_value_into(source, &mut target);
1485
1486        assert_eq!(
1487            target,
1488            json!({
1489                "unchanged": 1,
1490                "replaced_scalar": "new",
1491                "unioned_array": ["shared", "first", "second"],
1492                "inserted": ["brand-new"],
1493                "nested": {
1494                    "kept": true,
1495                    "plugins": [{ "name": "first-plugin" }, { "name": "second-plugin" }],
1496                    "scalar": 20,
1497                },
1498            })
1499        );
1500    }
1501}