util.rs

  1pub mod arc_cow;
  2pub mod codeberg;
  3pub mod fs;
  4mod git_author;
  5pub mod github;
  6pub mod http;
  7pub mod paths;
  8pub mod serde;
  9#[cfg(any(test, feature = "test-support"))]
 10pub mod test;
 11
 12use futures::Future;
 13use lazy_static::lazy_static;
 14use rand::{seq::SliceRandom, Rng};
 15use std::{
 16    borrow::Cow,
 17    cmp::{self, Ordering},
 18    env,
 19    ops::{AddAssign, Range, RangeInclusive},
 20    panic::Location,
 21    pin::Pin,
 22    task::{Context, Poll},
 23    time::Instant,
 24};
 25use unicase::UniCase;
 26
 27pub use take_until::*;
 28
 29#[macro_export]
 30macro_rules! debug_panic {
 31    ( $($fmt_arg:tt)* ) => {
 32        if cfg!(debug_assertions) {
 33            panic!( $($fmt_arg)* );
 34        } else {
 35            let backtrace = std::backtrace::Backtrace::capture();
 36            log::error!("{}\n{:?}", format_args!($($fmt_arg)*), backtrace);
 37        }
 38    };
 39}
 40
 41pub fn truncate(s: &str, max_chars: usize) -> &str {
 42    match s.char_indices().nth(max_chars) {
 43        None => s,
 44        Some((idx, _)) => &s[..idx],
 45    }
 46}
 47
 48pub fn http_proxy_from_env() -> Option<isahc::http::Uri> {
 49    macro_rules! try_env {
 50        ($($env:literal),+) => {
 51            $(
 52                if let Ok(env) = std::env::var($env) {
 53                    return env.parse::<isahc::http::Uri>().ok();
 54                }
 55            )+
 56        };
 57    }
 58
 59    try_env!(
 60        "ALL_PROXY",
 61        "all_proxy",
 62        "HTTPS_PROXY",
 63        "https_proxy",
 64        "HTTP_PROXY",
 65        "http_proxy"
 66    );
 67    None
 68}
 69
 70/// Removes characters from the end of the string if its length is greater than `max_chars` and
 71/// appends "..." to the string. Returns string unchanged if its length is smaller than max_chars.
 72pub fn truncate_and_trailoff(s: &str, max_chars: usize) -> String {
 73    debug_assert!(max_chars >= 5);
 74
 75    let truncation_ix = s.char_indices().map(|(i, _)| i).nth(max_chars);
 76    match truncation_ix {
 77        Some(length) => s[..length].to_string() + "",
 78        None => s.to_string(),
 79    }
 80}
 81
 82/// Removes characters from the front of the string if its length is greater than `max_chars` and
 83/// prepends the string with "...". Returns string unchanged if its length is smaller than max_chars.
 84pub fn truncate_and_remove_front(s: &str, max_chars: usize) -> String {
 85    debug_assert!(max_chars >= 5);
 86
 87    let truncation_ix = s.char_indices().map(|(i, _)| i).nth_back(max_chars);
 88    match truncation_ix {
 89        Some(length) => "".to_string() + &s[length..],
 90        None => s.to_string(),
 91    }
 92}
 93
 94/// Takes only `max_lines` from the string and, if there were more than `max_lines-1`, appends a
 95/// a newline and "..." to the string, so that `max_lines` are returned.
 96/// Returns string unchanged if its length is smaller than max_lines.
 97pub fn truncate_lines_and_trailoff(s: &str, max_lines: usize) -> String {
 98    let mut lines = s.lines().take(max_lines).collect::<Vec<_>>();
 99    if lines.len() > max_lines - 1 {
100        lines.pop();
101        lines.join("\n") + "\n"
102    } else {
103        lines.join("\n")
104    }
105}
106
107pub fn post_inc<T: From<u8> + AddAssign<T> + Copy>(value: &mut T) -> T {
108    let prev = *value;
109    *value += T::from(1);
110    prev
111}
112
113/// Extend a sorted vector with a sorted sequence of items, maintaining the vector's sort order and
114/// enforcing a maximum length. This also de-duplicates items. Sort the items according to the given callback. Before calling this,
115/// both `vec` and `new_items` should already be sorted according to the `cmp` comparator.
116pub fn extend_sorted<T, I, F>(vec: &mut Vec<T>, new_items: I, limit: usize, mut cmp: F)
117where
118    I: IntoIterator<Item = T>,
119    F: FnMut(&T, &T) -> Ordering,
120{
121    let mut start_index = 0;
122    for new_item in new_items {
123        if let Err(i) = vec[start_index..].binary_search_by(|m| cmp(m, &new_item)) {
124            let index = start_index + i;
125            if vec.len() < limit {
126                vec.insert(index, new_item);
127            } else if index < vec.len() {
128                vec.pop();
129                vec.insert(index, new_item);
130            }
131            start_index = index;
132        }
133    }
134}
135
136/// Parse the result of calling `usr/bin/env` with no arguments
137pub fn parse_env_output(env: &str, mut f: impl FnMut(String, String)) {
138    let mut current_key: Option<String> = None;
139    let mut current_value: Option<String> = None;
140
141    for line in env.split_terminator('\n') {
142        if let Some(separator_index) = line.find('=') {
143            if &line[..separator_index] != "" {
144                if let Some((key, value)) = Option::zip(current_key.take(), current_value.take()) {
145                    f(key, value)
146                }
147                current_key = Some(line[..separator_index].to_string());
148                current_value = Some(line[separator_index + 1..].to_string());
149                continue;
150            };
151        }
152        if let Some(value) = current_value.as_mut() {
153            value.push('\n');
154            value.push_str(line);
155        }
156    }
157    if let Some((key, value)) = Option::zip(current_key.take(), current_value.take()) {
158        f(key, value)
159    }
160}
161
162pub fn merge_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
163    use serde_json::Value;
164
165    match (source, target) {
166        (Value::Object(source), Value::Object(target)) => {
167            for (key, value) in source {
168                if let Some(target) = target.get_mut(&key) {
169                    merge_json_value_into(value, target);
170                } else {
171                    target.insert(key.clone(), value);
172                }
173            }
174        }
175
176        (source, target) => *target = source,
177    }
178}
179
180pub fn merge_non_null_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
181    use serde_json::Value;
182    if let Value::Object(source_object) = source {
183        let target_object = if let Value::Object(target) = target {
184            target
185        } else {
186            *target = Value::Object(Default::default());
187            target.as_object_mut().unwrap()
188        };
189        for (key, value) in source_object {
190            if let Some(target) = target_object.get_mut(&key) {
191                merge_non_null_json_value_into(value, target);
192            } else if !value.is_null() {
193                target_object.insert(key.clone(), value);
194            }
195        }
196    } else if !source.is_null() {
197        *target = source
198    }
199}
200
201pub fn measure<R>(label: &str, f: impl FnOnce() -> R) -> R {
202    lazy_static! {
203        pub static ref ZED_MEASUREMENTS: bool = env::var("ZED_MEASUREMENTS")
204            .map(|measurements| measurements == "1" || measurements == "true")
205            .unwrap_or(false);
206    }
207
208    if *ZED_MEASUREMENTS {
209        let start = Instant::now();
210        let result = f();
211        let elapsed = start.elapsed();
212        eprintln!("{}: {:?}", label, elapsed);
213        result
214    } else {
215        f()
216    }
217}
218
219pub trait ResultExt<E> {
220    type Ok;
221
222    fn log_err(self) -> Option<Self::Ok>;
223    /// Assert that this result should never be an error in development or tests.
224    fn debug_assert_ok(self, reason: &str) -> Self;
225    fn warn_on_err(self) -> Option<Self::Ok>;
226    fn inspect_error(self, func: impl FnOnce(&E)) -> Self;
227}
228
229impl<T, E> ResultExt<E> for Result<T, E>
230where
231    E: std::fmt::Debug,
232{
233    type Ok = T;
234
235    #[track_caller]
236    fn log_err(self) -> Option<T> {
237        match self {
238            Ok(value) => Some(value),
239            Err(error) => {
240                let caller = Location::caller();
241                log::error!("{}:{}: {:?}", caller.file(), caller.line(), error);
242                None
243            }
244        }
245    }
246
247    #[track_caller]
248    fn debug_assert_ok(self, reason: &str) -> Self {
249        if let Err(error) = &self {
250            debug_panic!("{reason} - {error:?}");
251        }
252        self
253    }
254
255    fn warn_on_err(self) -> Option<T> {
256        match self {
257            Ok(value) => Some(value),
258            Err(error) => {
259                log::warn!("{:?}", error);
260                None
261            }
262        }
263    }
264
265    /// https://doc.rust-lang.org/std/result/enum.Result.html#method.inspect_err
266    fn inspect_error(self, func: impl FnOnce(&E)) -> Self {
267        if let Err(err) = &self {
268            func(err);
269        }
270
271        self
272    }
273}
274
275pub trait TryFutureExt {
276    fn log_err(self) -> LogErrorFuture<Self>
277    where
278        Self: Sized;
279
280    fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
281    where
282        Self: Sized;
283
284    fn warn_on_err(self) -> LogErrorFuture<Self>
285    where
286        Self: Sized;
287    fn unwrap(self) -> UnwrapFuture<Self>
288    where
289        Self: Sized;
290}
291
292impl<F, T, E> TryFutureExt for F
293where
294    F: Future<Output = Result<T, E>>,
295    E: std::fmt::Debug,
296{
297    #[track_caller]
298    fn log_err(self) -> LogErrorFuture<Self>
299    where
300        Self: Sized,
301    {
302        let location = Location::caller();
303        LogErrorFuture(self, log::Level::Error, *location)
304    }
305
306    fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
307    where
308        Self: Sized,
309    {
310        LogErrorFuture(self, log::Level::Error, location)
311    }
312
313    #[track_caller]
314    fn warn_on_err(self) -> LogErrorFuture<Self>
315    where
316        Self: Sized,
317    {
318        let location = Location::caller();
319        LogErrorFuture(self, log::Level::Warn, *location)
320    }
321
322    fn unwrap(self) -> UnwrapFuture<Self>
323    where
324        Self: Sized,
325    {
326        UnwrapFuture(self)
327    }
328}
329
330#[must_use]
331pub struct LogErrorFuture<F>(F, log::Level, core::panic::Location<'static>);
332
333impl<F, T, E> Future for LogErrorFuture<F>
334where
335    F: Future<Output = Result<T, E>>,
336    E: std::fmt::Debug,
337{
338    type Output = Option<T>;
339
340    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
341        let level = self.1;
342        let location = self.2;
343        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
344        match inner.poll(cx) {
345            Poll::Ready(output) => Poll::Ready(match output {
346                Ok(output) => Some(output),
347                Err(error) => {
348                    log::log!(
349                        level,
350                        "{}:{}: {:?}",
351                        location.file(),
352                        location.line(),
353                        error
354                    );
355                    None
356                }
357            }),
358            Poll::Pending => Poll::Pending,
359        }
360    }
361}
362
363pub struct UnwrapFuture<F>(F);
364
365impl<F, T, E> Future for UnwrapFuture<F>
366where
367    F: Future<Output = Result<T, E>>,
368    E: std::fmt::Debug,
369{
370    type Output = T;
371
372    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
373        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
374        match inner.poll(cx) {
375            Poll::Ready(result) => Poll::Ready(result.unwrap()),
376            Poll::Pending => Poll::Pending,
377        }
378    }
379}
380
381pub struct Deferred<F: FnOnce()>(Option<F>);
382
383impl<F: FnOnce()> Deferred<F> {
384    /// Drop without running the deferred function.
385    pub fn abort(mut self) {
386        self.0.take();
387    }
388}
389
390impl<F: FnOnce()> Drop for Deferred<F> {
391    fn drop(&mut self) {
392        if let Some(f) = self.0.take() {
393            f()
394        }
395    }
396}
397
398/// Run the given function when the returned value is dropped (unless it's cancelled).
399#[must_use]
400pub fn defer<F: FnOnce()>(f: F) -> Deferred<F> {
401    Deferred(Some(f))
402}
403
404pub struct RandomCharIter<T: Rng> {
405    rng: T,
406    simple_text: bool,
407}
408
409impl<T: Rng> RandomCharIter<T> {
410    pub fn new(rng: T) -> Self {
411        Self {
412            rng,
413            simple_text: std::env::var("SIMPLE_TEXT").map_or(false, |v| !v.is_empty()),
414        }
415    }
416
417    pub fn with_simple_text(mut self) -> Self {
418        self.simple_text = true;
419        self
420    }
421}
422
423impl<T: Rng> Iterator for RandomCharIter<T> {
424    type Item = char;
425
426    fn next(&mut self) -> Option<Self::Item> {
427        if self.simple_text {
428            return if self.rng.gen_range(0..100) < 5 {
429                Some('\n')
430            } else {
431                Some(self.rng.gen_range(b'a'..b'z' + 1).into())
432            };
433        }
434
435        match self.rng.gen_range(0..100) {
436            // whitespace
437            0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.rng).copied(),
438            // two-byte greek letters
439            20..=32 => char::from_u32(self.rng.gen_range(('α' as u32)..('ω' as u32 + 1))),
440            // // three-byte characters
441            33..=45 => ['✋', '✅', '❌', '❎', '⭐']
442                .choose(&mut self.rng)
443                .copied(),
444            // // four-byte characters
445            46..=58 => ['🍐', '🏀', '🍗', '🎉'].choose(&mut self.rng).copied(),
446            // ascii letters
447            _ => Some(self.rng.gen_range(b'a'..b'z' + 1).into()),
448        }
449    }
450}
451
452/// Get an embedded file as a string.
453pub fn asset_str<A: rust_embed::RustEmbed>(path: &str) -> Cow<'static, str> {
454    match A::get(path).unwrap().data {
455        Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()),
456        Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()),
457    }
458}
459
460// copy unstable standard feature option unzip
461// https://github.com/rust-lang/rust/issues/87800
462// Remove when this ship in Rust 1.66 or 1.67
463pub fn unzip_option<T, U>(option: Option<(T, U)>) -> (Option<T>, Option<U>) {
464    match option {
465        Some((a, b)) => (Some(a), Some(b)),
466        None => (None, None),
467    }
468}
469
470/// Expands to an immediately-invoked function expression. Good for using the ? operator
471/// in functions which do not return an Option or Result.
472///
473/// Accepts a normal block, an async block, or an async move block.
474#[macro_export]
475macro_rules! maybe {
476    ($block:block) => {
477        (|| $block)()
478    };
479    (async $block:block) => {
480        (|| async $block)()
481    };
482    (async move $block:block) => {
483        (|| async move $block)()
484    };
485}
486
487pub trait RangeExt<T> {
488    fn sorted(&self) -> Self;
489    fn to_inclusive(&self) -> RangeInclusive<T>;
490    fn overlaps(&self, other: &Range<T>) -> bool;
491    fn contains_inclusive(&self, other: &Range<T>) -> bool;
492}
493
494impl<T: Ord + Clone> RangeExt<T> for Range<T> {
495    fn sorted(&self) -> Self {
496        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
497    }
498
499    fn to_inclusive(&self) -> RangeInclusive<T> {
500        self.start.clone()..=self.end.clone()
501    }
502
503    fn overlaps(&self, other: &Range<T>) -> bool {
504        self.start < other.end && other.start < self.end
505    }
506
507    fn contains_inclusive(&self, other: &Range<T>) -> bool {
508        self.start <= other.start && other.end <= self.end
509    }
510}
511
512impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
513    fn sorted(&self) -> Self {
514        cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
515    }
516
517    fn to_inclusive(&self) -> RangeInclusive<T> {
518        self.clone()
519    }
520
521    fn overlaps(&self, other: &Range<T>) -> bool {
522        self.start() < &other.end && &other.start <= self.end()
523    }
524
525    fn contains_inclusive(&self, other: &Range<T>) -> bool {
526        self.start() <= &other.start && &other.end <= self.end()
527    }
528}
529
530/// A way to sort strings with starting numbers numerically first, falling back to alphanumeric one,
531/// case-insensitive.
532///
533/// This is useful for turning regular alphanumerically sorted sequences as `1-abc, 10, 11-def, .., 2, 21-abc`
534/// into `1-abc, 2, 10, 11-def, .., 21-abc`
535#[derive(Debug, PartialEq, Eq)]
536pub struct NumericPrefixWithSuffix<'a>(i32, &'a str);
537
538impl<'a> NumericPrefixWithSuffix<'a> {
539    pub fn from_numeric_prefixed_str(str: &'a str) -> Option<Self> {
540        let i = str.chars().take_while(|c| c.is_ascii_digit()).count();
541        let (prefix, remainder) = str.split_at(i);
542
543        match prefix.parse::<i32>() {
544            Ok(prefix) => Some(NumericPrefixWithSuffix(prefix, remainder)),
545            Err(_) => None,
546        }
547    }
548}
549
550impl Ord for NumericPrefixWithSuffix<'_> {
551    fn cmp(&self, other: &Self) -> Ordering {
552        let NumericPrefixWithSuffix(num_a, remainder_a) = self;
553        let NumericPrefixWithSuffix(num_b, remainder_b) = other;
554        num_a
555            .cmp(num_b)
556            .then_with(|| UniCase::new(remainder_a).cmp(&UniCase::new(remainder_b)))
557    }
558}
559
560impl<'a> PartialOrd for NumericPrefixWithSuffix<'a> {
561    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
562        Some(self.cmp(other))
563    }
564}
565lazy_static! {
566    static ref EMOJI_REGEX: regex::Regex = regex::Regex::new("(\\p{Emoji}|\u{200D})").unwrap();
567}
568
569/// Returns true if the given string consists of emojis only.
570/// E.g. "👨‍👩‍👧‍👧👋" will return true, but "👋!" will return false.
571pub fn word_consists_of_emojis(s: &str) -> bool {
572    let mut prev_end = 0;
573    for capture in EMOJI_REGEX.find_iter(s) {
574        if capture.start() != prev_end {
575            return false;
576        }
577        prev_end = capture.end();
578    }
579    prev_end == s.len()
580}
581
582#[cfg(test)]
583mod tests {
584    use super::*;
585
586    #[test]
587    fn test_extend_sorted() {
588        let mut vec = vec![];
589
590        extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
591        assert_eq!(vec, &[21, 17, 13, 8, 1]);
592
593        extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
594        assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
595
596        extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
597        assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
598    }
599
600    #[test]
601    fn test_iife() {
602        fn option_returning_function() -> Option<()> {
603            None
604        }
605
606        let foo = maybe!({
607            option_returning_function()?;
608            Some(())
609        });
610
611        assert_eq!(foo, None);
612    }
613
614    #[test]
615    fn test_trancate_and_trailoff() {
616        assert_eq!(truncate_and_trailoff("", 5), "");
617        assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
618        assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
619        assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèè…");
620    }
621
622    #[test]
623    fn test_numeric_prefix_str_method() {
624        let target = "1a";
625        assert_eq!(
626            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
627            Some(NumericPrefixWithSuffix(1, "a"))
628        );
629
630        let target = "12ab";
631        assert_eq!(
632            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
633            Some(NumericPrefixWithSuffix(12, "ab"))
634        );
635
636        let target = "12_ab";
637        assert_eq!(
638            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
639            Some(NumericPrefixWithSuffix(12, "_ab"))
640        );
641
642        let target = "1_2ab";
643        assert_eq!(
644            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
645            Some(NumericPrefixWithSuffix(1, "_2ab"))
646        );
647
648        let target = "1.2";
649        assert_eq!(
650            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
651            Some(NumericPrefixWithSuffix(1, ".2"))
652        );
653
654        let target = "1.2_a";
655        assert_eq!(
656            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
657            Some(NumericPrefixWithSuffix(1, ".2_a"))
658        );
659
660        let target = "12.2_a";
661        assert_eq!(
662            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
663            Some(NumericPrefixWithSuffix(12, ".2_a"))
664        );
665
666        let target = "12a.2_a";
667        assert_eq!(
668            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
669            Some(NumericPrefixWithSuffix(12, "a.2_a"))
670        );
671    }
672
673    #[test]
674    fn test_numeric_prefix_with_suffix() {
675        let mut sorted = vec!["1-abc", "10", "11def", "2", "21-abc"];
676        sorted.sort_by_key(|s| {
677            NumericPrefixWithSuffix::from_numeric_prefixed_str(s).unwrap_or_else(|| {
678                panic!("Cannot convert string `{s}` into NumericPrefixWithSuffix")
679            })
680        });
681        assert_eq!(sorted, ["1-abc", "2", "10", "11def", "21-abc"]);
682
683        for numeric_prefix_less in ["numeric_prefix_less", "aaa", "~™£"] {
684            assert_eq!(
685                NumericPrefixWithSuffix::from_numeric_prefixed_str(numeric_prefix_less),
686                None,
687                "String without numeric prefix `{numeric_prefix_less}` should not be converted into NumericPrefixWithSuffix"
688            )
689        }
690    }
691
692    #[test]
693    fn test_word_consists_of_emojis() {
694        let words_to_test = vec![
695            ("👨‍👩‍👧‍👧👋🥒", true),
696            ("👋", true),
697            ("!👋", false),
698            ("👋!", false),
699            ("👋 ", false),
700            (" 👋", false),
701            ("Test", false),
702        ];
703
704        for (text, expected_result) in words_to_test {
705            assert_eq!(word_consists_of_emojis(text), expected_result);
706        }
707    }
708
709    #[test]
710    fn test_truncate_lines_and_trailoff() {
711        let text = r#"Line 1
712Line 2
713Line 3"#;
714
715        assert_eq!(
716            truncate_lines_and_trailoff(text, 2),
717            r#"Line 1
718…"#
719        );
720
721        assert_eq!(
722            truncate_lines_and_trailoff(text, 3),
723            r#"Line 1
724Line 2
725…"#
726        );
727
728        assert_eq!(
729            truncate_lines_and_trailoff(text, 4),
730            r#"Line 1
731Line 2
732Line 3"#
733        );
734    }
735}