lla 0.5.4

Blazing Fast and highly customizable ls Replacement with Superpowers
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
use crate::error::{LlaError, Result};
use chrono::{DateTime, NaiveDate, NaiveDateTime, Utc};
use serde::Serialize;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

#[derive(Clone, Debug, Serialize)]
pub struct NumericBound {
    pub value: u64,
    pub inclusive: bool,
}

#[derive(Clone, Debug, Serialize)]
pub struct NumericRange {
    pub min: Option<NumericBound>,
    pub max: Option<NumericBound>,
}

impl NumericRange {
    pub fn matches(&self, value: u64) -> bool {
        if let Some(bound) = &self.min {
            if bound.inclusive {
                if value < bound.value {
                    return false;
                }
            } else if value <= bound.value {
                return false;
            }
        }

        if let Some(bound) = &self.max {
            if bound.inclusive {
                if value > bound.value {
                    return false;
                }
            } else if value >= bound.value {
                return false;
            }
        }

        true
    }
}

#[derive(Clone, Debug, Serialize)]
pub struct TimeRange {
    pub earliest: Option<SystemTime>,
    pub latest: Option<SystemTime>,
}

impl TimeRange {
    pub fn matches_epoch_secs(&self, seconds: u64) -> bool {
        let timestamp = UNIX_EPOCH + Duration::from_secs(seconds);
        self.matches_timestamp(timestamp)
    }

    pub fn matches_timestamp(&self, timestamp: SystemTime) -> bool {
        if let Some(start) = self.earliest {
            if timestamp < start {
                return false;
            }
        }

        if let Some(end) = self.latest {
            if timestamp > end {
                return false;
            }
        }

        true
    }
}

pub fn parse_size_range(expr: &str) -> Result<NumericRange> {
    let trimmed = expr.trim();
    if trimmed.is_empty() {
        return Err(LlaError::Parse("Size filter cannot be empty".into()));
    }

    if let Some(rest) = trimmed.strip_prefix(">=") {
        return Ok(NumericRange {
            min: Some(NumericBound {
                value: parse_size_value(rest.trim())?,
                inclusive: true,
            }),
            max: None,
        });
    }

    if let Some(rest) = trimmed.strip_prefix('>') {
        return Ok(NumericRange {
            min: Some(NumericBound {
                value: parse_size_value(rest.trim())?,
                inclusive: false,
            }),
            max: None,
        });
    }

    if let Some(rest) = trimmed.strip_prefix("<=") {
        return Ok(NumericRange {
            min: None,
            max: Some(NumericBound {
                value: parse_size_value(rest.trim())?,
                inclusive: true,
            }),
        });
    }

    if let Some(rest) = trimmed.strip_prefix('<') {
        return Ok(NumericRange {
            min: None,
            max: Some(NumericBound {
                value: parse_size_value(rest.trim())?,
                inclusive: false,
            }),
        });
    }

    if let Some(rest) = trimmed.strip_prefix('=') {
        let value = parse_size_value(rest.trim())?;
        return Ok(NumericRange {
            min: Some(NumericBound {
                value,
                inclusive: true,
            }),
            max: Some(NumericBound {
                value,
                inclusive: true,
            }),
        });
    }

    if let Some(rest) = trimmed.strip_prefix("==") {
        let value = parse_size_value(rest.trim())?;
        return Ok(NumericRange {
            min: Some(NumericBound {
                value,
                inclusive: true,
            }),
            max: Some(NumericBound {
                value,
                inclusive: true,
            }),
        });
    }

    if let Some((start, end)) = trimmed.split_once("..") {
        let start = start.trim();
        let end = end.trim();

        let min = if start.is_empty() {
            None
        } else {
            Some(NumericBound {
                value: parse_size_value(start)?,
                inclusive: true,
            })
        };

        let max = if end.is_empty() {
            None
        } else {
            Some(NumericBound {
                value: parse_size_value(end)?,
                inclusive: true,
            })
        };

        let mut range = NumericRange { min, max };
        normalize_numeric_range(&mut range);
        return Ok(range);
    }

    let value = parse_size_value(trimmed)?;
    Ok(NumericRange {
        min: Some(NumericBound {
            value,
            inclusive: true,
        }),
        max: Some(NumericBound {
            value,
            inclusive: true,
        }),
    })
}

pub fn parse_time_range(expr: &str, now: SystemTime) -> Result<TimeRange> {
    let trimmed = expr.trim();
    if trimmed.is_empty() {
        return Err(LlaError::Parse("Time filter cannot be empty".into()));
    }

    if let Some(rest) = trimmed.strip_prefix(">=") {
        return Ok(TimeRange {
            earliest: Some(parse_time_point(rest.trim(), now)?),
            latest: None,
        });
    }

    if let Some(rest) = trimmed.strip_prefix('>') {
        return Ok(TimeRange {
            earliest: Some(parse_time_point(rest.trim(), now)?),
            latest: None,
        });
    }

    if let Some(rest) = trimmed.strip_prefix("<=") {
        return Ok(TimeRange {
            earliest: None,
            latest: Some(parse_time_point(rest.trim(), now)?),
        });
    }

    if let Some(rest) = trimmed.strip_prefix('<') {
        return Ok(TimeRange {
            earliest: None,
            latest: Some(parse_time_point(rest.trim(), now)?),
        });
    }

    if let Some((start, end)) = trimmed.split_once("..") {
        let start = start.trim();
        let end = end.trim();

        let earliest = if start.is_empty() {
            None
        } else {
            Some(parse_time_point(start, now)?)
        };

        let latest = if end.is_empty() {
            None
        } else {
            Some(parse_time_point(end, now)?)
        };

        let mut range = TimeRange { earliest, latest };
        normalize_time_range(&mut range);
        return Ok(range);
    }

    Ok(TimeRange {
        earliest: Some(parse_time_point(trimmed, now)?),
        latest: None,
    })
}

fn normalize_numeric_range(range: &mut NumericRange) {
    if let (Some(min), Some(max)) = (range.min.clone(), range.max.clone()) {
        if min.value > max.value {
            range.min = Some(max);
            range.max = Some(min);
        }
    }
}

fn normalize_time_range(range: &mut TimeRange) {
    if let (Some(start), Some(end)) = (range.earliest.clone(), range.latest.clone()) {
        if start > end {
            range.earliest = Some(end);
            range.latest = Some(start);
        }
    }
}

fn parse_size_value(token: &str) -> Result<u64> {
    let cleaned = token.replace('_', "");
    let mut num_part = String::new();
    let mut suffix_part = String::new();
    for ch in cleaned.chars() {
        if ch.is_ascii_digit() || ch == '.' {
            if !suffix_part.is_empty() {
                suffix_part.push(ch);
            } else {
                num_part.push(ch);
            }
        } else if ch.is_ascii_alphabetic() {
            suffix_part.push(ch);
        } else {
            return Err(LlaError::Parse(format!(
                "Unexpected character '{}' in size literal '{}'",
                ch, token
            )));
        }
    }

    if num_part.is_empty() {
        return Err(LlaError::Parse(format!(
            "Missing numeric value in size literal '{}'",
            token
        )));
    }

    let value: f64 = num_part.parse().map_err(|_| {
        LlaError::Parse(format!(
            "Invalid numeric portion in size literal '{}'",
            token
        ))
    })?;

    let multiplier = size_multiplier(suffix_part.trim())?;
    let bytes = value * multiplier as f64;
    if bytes.is_sign_negative() {
        return Err(LlaError::Parse(format!(
            "Size literal '{}' must be positive",
            token
        )));
    }

    Ok(bytes.round() as u64)
}

fn size_multiplier(unit: &str) -> Result<u64> {
    if unit.is_empty() || unit.eq_ignore_ascii_case("b") {
        return Ok(1);
    }

    let normalized = unit.to_ascii_lowercase();
    let multiplier = match normalized.as_str() {
        "k" | "kb" => 1024u64,
        "m" | "mb" => 1024u64.pow(2),
        "g" | "gb" => 1024u64.pow(3),
        "t" | "tb" => 1024u64.pow(4),
        "p" | "pb" => 1024u64.pow(5),
        "ki" | "kib" => 1024u64,
        "mi" | "mib" => 1024u64.pow(2),
        "gi" | "gib" => 1024u64.pow(3),
        "ti" | "tib" => 1024u64.pow(4),
        "pi" | "pib" => 1024u64.pow(5),
        _ => {
            return Err(LlaError::Parse(format!(
                "Unknown size suffix '{}' (use B, K, M, G, T, P, KiB, MiB, ...)",
                unit
            )))
        }
    };
    Ok(multiplier)
}

fn parse_time_point(input: &str, now: SystemTime) -> Result<SystemTime> {
    let trimmed = input.trim();
    if let Ok(abs) = parse_absolute_datetime(trimmed) {
        return Ok(abs);
    }

    if let Some(duration) = parse_duration(trimmed)? {
        return now.checked_sub(duration).ok_or_else(|| {
            LlaError::Parse(format!("Relative time '{}' exceeds supported range", input))
        });
    }

    Err(LlaError::Parse(format!(
        "Unable to parse date/time '{}'",
        input
    )))
}

fn parse_duration(token: &str) -> Result<Option<Duration>> {
    if token.is_empty() {
        return Ok(None);
    }

    let mut num_part = String::new();
    let mut unit_part = String::new();
    for ch in token.chars() {
        if ch.is_ascii_digit() || ch == '.' {
            if !unit_part.is_empty() {
                return Err(LlaError::Parse(format!(
                    "Invalid duration literal '{}'",
                    token
                )));
            }
            num_part.push(ch);
        } else if ch.is_ascii_alphabetic() {
            unit_part.push(ch);
        } else {
            return Err(LlaError::Parse(format!(
                "Invalid duration literal '{}'",
                token
            )));
        }
    }

    if num_part.is_empty() || unit_part.is_empty() {
        return Ok(None);
    }

    let value: f64 = num_part
        .parse()
        .map_err(|_| LlaError::Parse(format!("Invalid numeric portion in duration '{}'", token)))?;
    let unit = unit_part.to_ascii_lowercase();
    let seconds_per_unit = match unit.as_str() {
        "s" | "sec" | "secs" | "second" | "seconds" => 1.0,
        "m" | "min" | "mins" | "minute" | "minutes" => 60.0,
        "h" | "hr" | "hrs" | "hour" | "hours" => 3600.0,
        "d" | "day" | "days" => 86400.0,
        "w" | "wk" | "wks" | "week" | "weeks" => 604800.0,
        "mo" | "month" | "months" => 2_592_000.0, // 30 days
        "y" | "yr" | "yrs" | "year" | "years" => 31_536_000.0, // 365 days
        _ => {
            return Err(LlaError::Parse(format!(
                "Unknown duration unit '{}' in '{}'",
                unit, token
            )))
        }
    };

    let seconds = value * seconds_per_unit;
    if seconds.is_sign_negative() {
        return Err(LlaError::Parse(format!(
            "Duration '{}' must be positive",
            token
        )));
    }

    Ok(Some(Duration::from_secs_f64(seconds)))
}

fn parse_absolute_datetime(input: &str) -> Result<SystemTime> {
    if let Ok(dt) = DateTime::parse_from_rfc3339(input) {
        return datetime_to_system_time(dt.with_timezone(&Utc));
    }

    let naive_formats = [
        "%Y-%m-%d %H:%M:%S",
        "%Y-%m-%d %H:%M",
        "%Y-%m-%dT%H:%M:%S",
        "%Y-%m-%dT%H:%M",
    ];

    for fmt in naive_formats {
        if let Ok(naive) = NaiveDateTime::parse_from_str(input, fmt) {
            let dt = DateTime::<Utc>::from_naive_utc_and_offset(naive, Utc);
            return datetime_to_system_time(dt);
        }
    }

    if let Ok(date) = NaiveDate::parse_from_str(input, "%Y-%m-%d") {
        if let Some(naive) = date.and_hms_opt(0, 0, 0) {
            let dt = DateTime::<Utc>::from_naive_utc_and_offset(naive, Utc);
            return datetime_to_system_time(dt);
        }
    }

    Err(LlaError::Parse(format!(
        "Unable to parse date/time '{}'. Use ISO8601 or relative durations (e.g., 2023-01-01, 2023-01-01T12:00, 7d, <3h).",
        input
    )))
}

fn datetime_to_system_time(dt: DateTime<Utc>) -> Result<SystemTime> {
    if dt.timestamp() < 0 {
        return Err(LlaError::Parse(
            "Dates before 1970-01-01 are not supported".to_string(),
        ));
    }

    let secs = dt.timestamp() as u64;
    let nanos = dt.timestamp_subsec_nanos() as u64;
    Ok(UNIX_EPOCH + Duration::from_secs(secs) + Duration::from_nanos(nanos))
}