tailtales 0.2.3

Flexible log viewer for logfmt and other formats with LUA scripting, filtering, filtering expressions, and real-time pipe following.
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
use ratatui::style::{Color, Style};
use serde::{de::Deserializer, Deserialize, Serialize};
use std::{collections::HashMap, path::PathBuf, str::FromStr};

use crate::{ast, lua_engine::LuaEngine};

// singleton load settings

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct Settings {
    #[serde(default)]
    pub global: GlobalSettings,
    #[serde(default)]
    pub rules: Vec<RulesSettings>,
    #[serde(default)]
    pub default_arguments: Vec<String>,
    #[serde(default)]
    pub keybindings: HashMap<String, String>,
    #[serde(default)]
    pub colors: GlobalColorSettings,
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct SettingsFromYaml {
    #[serde(default)]
    pub global: Option<GlobalSettings>,
    #[serde(default)]
    pub rules: Vec<RulesSettings>,
    #[serde(default)]
    pub default_arguments: Vec<String>,
    #[serde(default)]
    pub keybindings: Option<HashMap<String, String>>,
    #[serde(default)]
    pub colors: Option<GlobalColorSettings>,
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct GlobalSettings {
    // pub reload_on_truncate: bool,
    pub gutter_symbol: String,
    #[serde(default)]
    pub symbols: SymbolSettings,
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct SymbolSettings {
    #[serde(default = "default_tag_initial")]
    pub tag_initial: String,
    #[serde(default = "default_tag_mid_left")]
    pub tag_mid_left: String,
    #[serde(default = "default_tag_mid_right")]
    pub tag_mid_right: String,
    #[serde(default = "default_tag_end")]
    pub tag_end: String,
}

fn default_tag_initial() -> String {
    "[".to_string()
}

fn default_tag_mid_left() -> String {
    ":".to_string()
}

fn default_tag_mid_right() -> String {
    " ".to_string()
}

fn default_tag_end() -> String {
    "]".to_string()
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct GlobalColorSettings {
    #[serde(deserialize_with = "parse_style", serialize_with = "serialize_style")]
    pub normal: Style,
    #[serde(deserialize_with = "parse_style", serialize_with = "serialize_style")]
    pub highlight: Style,
    #[serde(deserialize_with = "parse_style", serialize_with = "serialize_style")]
    pub mark: Style,
    #[serde(
        deserialize_with = "parse_style",
        serialize_with = "serialize_style",
        default = "default_highlight"
    )]
    pub mark_highlight: Style,
    pub details: DetailsColorSettings,
    pub table: TableColorSettings,
    pub footer: FooterColorSettings,
}

fn default_highlight() -> Style {
    Style::new().fg(Color::White).bg(Color::Black)
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct FooterColorSettings {
    #[serde(deserialize_with = "parse_style", serialize_with = "serialize_style")]
    pub command: Style,
    #[serde(deserialize_with = "parse_style", serialize_with = "serialize_style")]
    pub filter: Style,
    #[serde(deserialize_with = "parse_style", serialize_with = "serialize_style")]
    pub search: Style,
    #[serde(deserialize_with = "parse_style", serialize_with = "serialize_style")]
    pub version: Style,
    #[serde(deserialize_with = "parse_style", serialize_with = "serialize_style")]
    pub rule: Style,
    #[serde(deserialize_with = "parse_style", serialize_with = "serialize_style")]
    pub line_number: Style,
    #[serde(deserialize_with = "parse_style", serialize_with = "serialize_style")]
    pub other: Style,
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct TableColorSettings {
    #[serde(deserialize_with = "parse_style", serialize_with = "serialize_style")]
    pub header: Style,
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct DetailsColorSettings {
    #[serde(deserialize_with = "parse_style", serialize_with = "serialize_style")]
    pub title: Style,
    #[serde(deserialize_with = "parse_style", serialize_with = "serialize_style")]
    pub key: Style,
    #[serde(deserialize_with = "parse_style", serialize_with = "serialize_style")]
    pub value: Style,
    #[serde(deserialize_with = "parse_style", serialize_with = "serialize_style")]
    pub border: Style,
}

#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Clone)]
pub enum Alignment {
    #[default]
    Left,
    Right,
    Center,
}

#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct RulesSettings {
    pub name: String,
    #[serde(default)]
    pub file_patterns: Vec<String>,
    #[serde(default)]
    pub extractors: Vec<String>,
    #[serde(default)]
    pub filters: Vec<FilterSettings>,
    #[serde(default)]
    pub columns: Vec<ColumnSettings>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(deny_unknown_fields)]
pub struct FilterSettings {
    #[serde(default)]
    pub name: Option<String>,
    #[serde(
        default,
        deserialize_with = "parse_expression",
        serialize_with = "serialize_expression"
    )]
    pub expression: ast::AST,
    #[serde(
        default,
        deserialize_with = "parse_optional_style",
        serialize_with = "serialize_optional_style"
    )]
    pub highlight: Option<Style>,
    #[serde(
        default,
        deserialize_with = "parse_optional_style",
        serialize_with = "serialize_optional_style"
    )]
    pub gutter: Option<Style>,
    #[serde(default)]
    pub gutter_symbol: String,
}

fn parse_expression<'de, D>(deserializer: D) -> Result<ast::AST, D::Error>
where
    D: Deserializer<'de>,
{
    let s: String = Deserialize::deserialize(deserializer)?;
    ast::AST::from_str(&s).map_err(serde::de::Error::custom)
}

fn serialize_expression<S>(expression: &ast::AST, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    serializer.serialize_str(&expression.to_string())
}

fn parse_style<'de, D>(deserializer: D) -> Result<Style, D::Error>
where
    D: Deserializer<'de>,
{
    let s: String = Deserialize::deserialize(deserializer)?;
    string_to_style(&s).map_err(serde::de::Error::custom)
}

pub fn string_to_style(s: &str) -> Result<Style, String> {
    let mut parts = s.split_whitespace();
    let first = parts.next().ok_or_else(|| "Missing first color")?;
    let first_color = Color::from_str(first).map_err(|_| "Invalid color")?;
    let style = Style::new().fg(first_color);

    // optional second, default black
    let style = match parts.next() {
        Some(second) => {
            let second_color = Color::from_str(second).map_err(|_| "Invalid color")?;
            style.bg(second_color)
        }
        None => style,
    };

    Ok(style)
}

fn serialize_style<S>(style: &Style, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    let mut s = String::new();
    if let Some(fg) = style.fg {
        s.push_str(&fg.to_string());
        if let Some(bg) = style.bg {
            s.push(' ');
            s.push_str(&bg.to_string());
        }
    }
    serializer.serialize_str(&s)
}

fn parse_optional_style<'de, D>(deserializer: D) -> Result<Option<Style>, D::Error>
where
    D: Deserializer<'de>,
{
    let s: String = Deserialize::deserialize(deserializer)?;
    if s.is_empty() {
        Ok(None)
    } else {
        let style = string_to_style(&s).map_err(serde::de::Error::custom)?;
        Ok(Some(style))
    }
}

fn serialize_optional_style<S>(style: &Option<Style>, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    match style {
        Some(style) => serialize_style(style, serializer),
        None => serializer.serialize_none(),
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ColumnSettings {
    pub name: String,
    pub width: usize,
    #[serde(
        default,
        deserialize_with = "parse_alignment",
        serialize_with = "serialize_alignment"
    )]
    pub align: Alignment,
}

impl FromStr for Alignment {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "left" => Ok(Alignment::Left),
            "right" => Ok(Alignment::Right),
            "center" => Ok(Alignment::Center),
            _ => Err(()),
        }
    }
}

fn parse_alignment<'de, D>(deserializer: D) -> Result<Alignment, D::Error>
where
    D: Deserializer<'de>,
{
    let s: String = Deserialize::deserialize(deserializer)?;
    Alignment::from_str(&s).map_err(|_| serde::de::Error::custom("Invalid alignment"))
}

fn serialize_alignment<S>(align: &Alignment, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    serializer.serialize_str(match align {
        Alignment::Left => "left",
        Alignment::Right => "right",
        Alignment::Center => "center",
    })
}

impl Settings {
    pub fn new() -> Result<Settings, Box<dyn std::error::Error>> {
        let mut settings = Settings::default();

        settings.read_from_string(Self::default_settings_yaml_data())?;

        // Try to load from ~/.config/tailtales/settings.yaml. If does not exist, ignore.

        let filename = Self::local_settings_filename();

        if let Some(filename) = filename {
            if filename.exists() {
                settings
                    .read_from_yaml(filename.to_str().unwrap_or("unknown"))
                    .map_err(|e| {
                        format!("Error reading settings from {}: {}", filename.display(), e)
                    })?;
            }
        }

        Ok(settings)
    }
    pub fn default_settings_yaml_data() -> &'static str {
        include_str!("../settings.yaml")
    }

    pub fn local_settings_filename() -> Option<PathBuf> {
        let xdg = xdg::BaseDirectories::with_prefix("tailtales");

        if xdg.is_err() {
            return None;
        }

        xdg.unwrap().find_config_file("settings.yaml")
    }

    #[allow(dead_code)]
    pub fn save_default_settings(&self) -> Result<(), Box<dyn std::error::Error>> {
        let xdg = xdg::BaseDirectories::with_prefix("tailtales")?;
        let path = xdg.place_config_file("settings.yaml")?;
        let filecontents = Self::default_settings_yaml_data();
        std::fs::write(path, filecontents)?;

        Ok(())
    }

    pub fn read_from_yaml(&mut self, filename: &str) -> Result<(), Box<dyn std::error::Error>> {
        let file = std::fs::File::open(filename)?;
        let reader = std::io::BufReader::new(file);
        let settings: SettingsFromYaml = serde_yaml::from_reader(reader)?;

        self.merge_with(settings);

        Ok(())
    }

    pub fn read_from_string(&mut self, s: &str) -> Result<(), Box<dyn std::error::Error>> {
        let settings: SettingsFromYaml = serde_yaml::from_str(s)?;
        self.merge_with(settings);

        Ok(())
    }

    pub fn merge_with(&mut self, other: SettingsFromYaml) {
        if other.global.is_some() {
            self.global = other.global.unwrap();
        }

        if other.default_arguments.len() > 0 {
            self.default_arguments = other.default_arguments.clone();
        }

        let mut other_rules = other.rules.clone();
        other_rules.extend(self.rules.clone());

        if other.keybindings.is_some() {
            self.keybindings.extend(other.keybindings.unwrap());
        }

        if other.colors.is_some() {
            let other_colors = other.colors.unwrap();
            self.colors.normal = other_colors.normal;
            self.colors.highlight = other_colors.highlight;
            self.colors.mark = other_colors.mark;
            self.colors.mark_highlight = other_colors.mark_highlight;
            self.colors.details = other_colors.details;
            self.colors.table = other_colors.table;
            self.colors.footer = other_colors.footer;
        }

        self.rules = other_rules
    }

    /// Compile all keybinding scripts in the Lua engine
    /// This is called during settings loading to pre-compile all Lua scripts
    pub fn compile_keybinding_scripts(&self, lua_engine: &mut LuaEngine) -> Result<(), String> {
        let mut failed_scripts = Vec::new();

        for (key_name, script) in &self.keybindings {
            // Create a unique script name for the keybinding
            let script_name = format!(
                "keybinding_{}",
                key_name.replace("-", "_").replace(" ", "_")
            );

            match lua_engine.compile_script(&script_name, script) {
                Ok(_) => {
                    log::debug!(
                        "Compiled keybinding script for key '{}': {}",
                        key_name,
                        script
                    );
                }
                Err(e) => {
                    log::error!(
                        "Failed to compile keybinding script for key '{}': {}",
                        key_name,
                        e
                    );
                    failed_scripts.push(format!("Key '{}': {}", key_name, e));
                }
            }
        }

        if !failed_scripts.is_empty() {
            return Err(format!(
                "Failed to compile {} keybinding scripts:\n{}",
                failed_scripts.len(),
                failed_scripts.join("\n")
            ));
        }

        log::info!(
            "Successfully compiled {} keybinding scripts",
            self.keybindings.len()
        );
        Ok(())
    }

    /// Get the script name for a specific keybinding
    pub fn get_keybinding_script_name(key_name: &str) -> String {
        format!(
            "keybinding_{}",
            key_name.replace("-", "_").replace(" ", "_")
        )
    }
}

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

    // #[test]
    // fn test_parse_style() {
    //     let input = "white black";
    //     let result = parse_style(input.into()).unwrap();
    //     assert_eq!(result, (Color::White, Color::Black));
    // }

    // #[test]
    // fn test_parse_color() {
    //     let input = "white";
    //     let result = parse_color(input.into()).unwrap();
    //     assert_eq!(result, Some(Color::White));
    // }

    // #[test]
    // fn test_parse_alignment() {
    //     let input = "left";
    //     let result = parse_alignment(input.into()).unwrap();
    //     assert_eq!(result, Alignment::Left);
    // }

    #[test]
    fn test_parse_settings() {
        let mut settings = Settings::new().unwrap();
        settings.read_from_yaml("settings.yaml").unwrap();
        println!("{:#?}", settings);
    }
}