slumber_util 5.3.0

Common utilities used across several subcrates of Slumber. Not for external use.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! Common utilities that aren't specific to one other subcrate and are unlikely
//! to change frequently. The main purpose of this is to pull logic out of the
//! core crate, because that one changes a lot and requires constant
//! recompilation.
//!
//! **This crate is not semver compliant**. The version is locked to the root
//! `slumber` crate version. If you choose to depend directly on this crate, you
//! do so at your own risk of breakage.

pub mod paths;
#[cfg(any(test, feature = "test"))]
mod test_util;
pub mod yaml;

#[cfg(any(test, feature = "test"))]
pub use test_util::*;

use itertools::Itertools;
use serde::{
    Deserialize, Serialize, Serializer, de::Error as _, ser::SerializeMap,
};
use std::{
    error::Error,
    fmt::{self, Debug, Display},
    fs::{File, OpenOptions},
    io,
    ops::Deref,
    str::FromStr,
    time::Duration,
};
use tracing::{error, level_filters::LevelFilter};
use tracing_subscriber::{
    Layer, fmt::format::FmtSpan, layer::SubscriberExt, util::SubscriberInitExt,
};
use winnow::{
    ModalResult, Parser,
    ascii::digit1,
    combinator::{alt, repeat},
};

/// Link to the GitHub New Issue form
pub const NEW_ISSUE_LINK: &str =
    "https://github.com/LucasPickering/slumber/issues/new";

/// A static mapping between values (of type `T`) and labels (strings). Used to
/// both stringify from and parse to `T`.
pub struct Mapping<'a, T: Copy>(&'a [(T, &'a [&'a str])]);

impl<'a, T: Copy> Mapping<'a, T> {
    /// Construct a new mapping
    pub const fn new(mapping: &'a [(T, &'a [&'a str])]) -> Self {
        Self(mapping)
    }

    /// Get a value by one of its labels
    pub fn get(&self, s: &str) -> Option<T> {
        for (value, strs) in self.0 {
            for other_string in *strs {
                if *other_string == s {
                    return Some(*value);
                }
            }
        }
        None
    }

    /// Get the label mapped to a value. If it has multiple labels, use the
    /// first. Return `None` if the value isn't in the map or has no labels
    pub fn get_label(&self, value: T) -> Option<&str>
    where
        T: Debug + PartialEq,
    {
        let (_, strings) = self.0.iter().find(|(v, _)| v == &value)?;
        strings.first().copied()
    }

    /// Get all available mapped strings
    pub fn all_strings(&self) -> impl Iterator<Item = &str> {
        self.0
            .iter()
            .flat_map(|(_, strings)| strings.iter().copied())
    }
}

/// Extension trait for [Option]
pub trait OptionExt<T> {
    /// Map an option with a fallible function
    ///
    /// `option.try_map(f)` is equivalent to `option.map(f).transpose()`
    fn try_map<U, E>(
        self,
        f: impl FnOnce(T) -> Result<U, E>,
    ) -> Result<Option<U>, E>;
}

impl<T> OptionExt<T> for Option<T> {
    fn try_map<U, E>(
        self,
        f: impl FnOnce(T) -> Result<U, E>,
    ) -> Result<Option<U>, E> {
        self.map(f).transpose()
    }
}

/// Extension trait for [Result]
pub trait ResultTraced<T, E>: Sized {
    /// If this is an error, trace it. Return the same result.
    #[must_use]
    fn traced(self) -> Self;
}

impl<T, E: 'static + Error> ResultTraced<T, E> for Result<T, E> {
    fn traced(self) -> Self {
        self.inspect_err(|err| error!(error = err as &dyn Error))
    }
}

/// [ResultTraced] but for the `anyhow` result. This has to be a separate trait
/// because we can't put a blanket impl on std `Error` *and* `anyhow::Result`,
/// as the two "could" conflict in the future.
pub trait ResultTracedAnyhow<T, E>: Sized {
    /// If this is an error, trace it. Return the same result.
    #[must_use]
    fn traced(self) -> Self;
}

// A blanket impl that covers `anyhow::Error` without actually referring to it.
// This allows us to omit anyhow as a dependency, so downstream consumers don't
// pull it in unless they need it.
impl<T, E> ResultTracedAnyhow<T, E> for Result<T, E>
where
    E: Deref<Target = dyn Error + Send + Sync>,
{
    fn traced(self) -> Self {
        self.inspect_err(|err| error!(error = err.deref()))
    }
}

/// Get a link to a page on the doc website. This will append the doc prefix,
/// as well as the suffix.
///
/// ```
/// use slumber_util::doc_link;
/// assert_eq!(
///     doc_link("api/chain"),
///     "https://slumber.lucaspickering.me/api/chain.html",
/// );
/// ```
pub fn doc_link(path: &str) -> String {
    const ROOT: &str = "https://slumber.lucaspickering.me/";
    if path.is_empty() {
        ROOT.into()
    } else {
        format!("{ROOT}{path}.html")
    }
}

/// Get a link to a file in the remote git repo. This is the raw link, not the
/// fancy UI link. It will be pinned to tag of the current crate version.
pub fn git_link(path: &str) -> String {
    format!(
        "https://raw.githubusercontent.com\
        /LucasPickering/slumber/refs/tags/v{version}/{path}",
        version = env!("CARGO_PKG_VERSION"),
    )
}

/// A newtype for [Duration] that provides formatting, parsing, and
/// deserialization. The name is meant to make it harder to confuse with
/// [Duration].
#[derive(Copy, Clone, Debug, Eq, derive_more::From, PartialEq)]
pub struct TimeSpan(Duration);

impl TimeSpan {
    /// Get the inner [Duration]
    pub fn inner(self) -> Duration {
        self.0
    }
}

impl Display for TimeSpan {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Use the largest units possible
        let mut remaining = self.0.as_secs();

        // Make sure 0 doesn't give us an empty string
        if remaining == 0 {
            return write!(f, "0s");
        }

        // Start with the biggest units
        let units = DurationUnit::ALL
            .iter()
            .sorted_by_key(|unit| unit.seconds())
            .rev();
        for unit in units {
            let quantity = remaining / unit.seconds();
            if quantity > 0 {
                remaining %= unit.seconds();
                write!(f, "{quantity}{unit}")?;
            }
        }
        Ok(())
    }
}

impl FromStr for TimeSpan {
    type Err = TimeSpanParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        fn quantity(input: &mut &str) -> ModalResult<u64> {
            digit1.parse_to().parse_next(input)
        }

        fn unit(input: &mut &str) -> ModalResult<DurationUnit> {
            alt((
                "s".map(|_| DurationUnit::Second),
                "m".map(|_| DurationUnit::Minute),
                "h".map(|_| DurationUnit::Hour),
                "d".map(|_| DurationUnit::Day),
            ))
            .parse_next(input)
        }

        // Parse one or more quantity-unit pairs and sum them all up
        let seconds = repeat(1.., (quantity, unit))
            .fold(
                || 0,
                |acc, (quantity, unit)| acc + (quantity * unit.seconds()),
            )
            .parse(s)
            .map_err(|_| TimeSpanParseError)?;

        Ok(Self(Duration::from_secs(seconds)))
    }
}

impl<'de> Deserialize<'de> for TimeSpan {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        s.parse().map_err(D::Error::custom)
    }
}

/// Error for [TimeSpan]'s `FromStr` impl
#[derive(Debug)]
pub struct TimeSpanParseError;

impl Display for TimeSpanParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // The format is so simple there isn't much value in spitting out a
        // specific parsing error, just use a canned one
        write!(
            f,
            "Invalid duration, must be `(<quantity><unit>)+` \
                (e.g. `12d` or `1h30m`). Units are {}",
            DurationUnit::ALL
                .iter()
                .format_with(", ", |unit, f| f(&format_args!("`{unit}`")))
        )
    }
}

impl Error for TimeSpanParseError {}

/// Supported units for duration parsing/formatting
#[derive(Debug)]
enum DurationUnit {
    Second,
    Minute,
    Hour,
    Day,
}

impl DurationUnit {
    const ALL: &[Self] = &[Self::Second, Self::Minute, Self::Hour, Self::Day];

    fn seconds(&self) -> u64 {
        match self {
            DurationUnit::Second => 1,
            DurationUnit::Minute => 60,
            DurationUnit::Hour => 60 * 60,
            DurationUnit::Day => 60 * 60 * 24,
        }
    }
}

impl Display for DurationUnit {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Second => write!(f, "s"),
            Self::Minute => write!(f, "m"),
            Self::Hour => write!(f, "h"),
            Self::Day => write!(f, "d"),
        }
    }
}

/// Set up tracing to a log file, and optionally stderr as well. If there's
/// an error creating the log file, we'll skip that part. This means in the TUI
/// the error (and all other tracing) will never be visible, but that's a
/// problem for another day.
pub fn initialize_tracing(level_filter: LevelFilter, has_stderr: bool) {
    /// Create a new log file in a temporary directory. Each file gets a unique
    /// name so this won't clobber any old files.
    fn initialize_log_file() -> io::Result<File> {
        let path = paths::log_file();
        paths::create_parent(&path)?;
        let log_file = OpenOptions::new()
            .create(true)
            .truncate(true)
            .write(true)
            .open(path)?;
        Ok(log_file)
    }

    // Failing to log shouldn't be a fatal crash, so just move on
    let log_file = initialize_log_file().traced().ok();

    let file_subscriber = log_file.map(|log_file| {
        // Include PID
        // https://github.com/tokio-rs/tracing/pull/2655
        tracing_subscriber::fmt::layer()
            .with_file(true)
            .with_line_number(true)
            .with_writer(log_file)
            .with_target(false)
            .with_ansi(false)
            .with_span_events(FmtSpan::NONE)
            // File output can't be lower than warn. There's no good reason to
            // disable file output. If someone passes off/error, they probably
            // just want to set the stderr level.
            .with_filter(level_filter.max(LevelFilter::WARN))
    });

    // Enable console output for CLI. By default logging is off, but it can be
    // turned up with the verbose flag
    let stderr_subscriber = tracing_subscriber::fmt::layer()
        .with_writer(io::stderr)
        .with_target(false)
        .with_span_events(FmtSpan::NONE)
        .without_time()
        // Disable stderr for TUI mode
        .with_filter(if has_stderr {
            level_filter
        } else {
            LevelFilter::OFF
        });

    #[cfg(feature = "tokio_tracing")]
    {
        tracing_subscriber::registry()
            .with(file_subscriber)
            .with(stderr_subscriber)
            .with(console_subscriber::spawn())
            .init();
    }
    #[cfg(not(feature = "tokio_tracing"))]
    {
        tracing_subscriber::registry()
            .with(file_subscriber)
            .with(stderr_subscriber)
            .init();
    }
}

/// Serialize a list of tuples as a mapping
///
/// This is used in a few spots where data is stored internally as `Vec<(K, V)>`
/// but needs to serialize as a mapping, rather than a sequence.
pub fn serialize_mapping<S, K, V>(
    input: &Vec<(K, V)>,
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    S: Serializer,
    K: Serialize,
    V: Serialize,
{
    let mut map = serializer.serialize_map(Some(input.len()))?;
    for (k, v) in input {
        map.serialize_entry(k, v)?;
    }
    map.end()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::assert_err;
    use rstest::rstest;

    #[rstest]
    #[case::zero(Duration::from_secs(0), "0s")]
    #[case::seconds_short(Duration::from_secs(3), "3s")]
    #[case::seconds_hour(Duration::from_secs(3600), "1h")]
    #[case::seconds_composite(Duration::from_secs(3690), "1h1m30s")]
    // Subsecond precision is lost
    #[case::seconds_subsecond_lost(Duration::from_millis(400), "0s")]
    #[case::seconds_subsecond_round_down(Duration::from_millis(1999), "1s")]
    fn test_time_span_to_string(
        #[case] duration: Duration,
        #[case] expected: &'static str,
    ) {
        assert_eq!(&TimeSpan(duration).to_string(), expected);
    }

    #[rstest]
    #[case::seconds_zero("0s", Duration::from_secs(0))]
    #[case::seconds_short("1s", Duration::from_secs(1))]
    #[case::seconds_longer("100s", Duration::from_secs(100))]
    #[case::minutes("3m", Duration::from_secs(180))]
    #[case::hours("3h", Duration::from_secs(10_800))]
    #[case::days("2d", Duration::from_secs(172_800))]
    #[case::composite("2d3h10m17s", Duration::from_secs(
        2 * 86400 + 3 * 3600 + 10 * 60 + 17
    ))]
    fn test_time_span_parse(
        #[case] s: &'static str,
        #[case] expected: Duration,
    ) {
        assert_eq!(s.parse::<TimeSpan>().unwrap(), TimeSpan(expected));
    }

    #[rstest]
    #[case::negative("-1s", "Invalid duration")]
    #[case::whitespace(" 1s ", "Invalid duration")]
    #[case::trailing_whitespace("1s ", "Invalid duration")]
    #[case::decimal("3.5s", "Invalid duration")]
    #[case::invalid_unit("3hr", "Units are `s`, `m`, `h`, `d`")]
    fn test_time_span_parse_error(
        #[case] s: &'static str,
        #[case] expected_error: &str,
    ) {
        assert_err(s.parse::<TimeSpan>(), expected_error);
    }
}