gex 0.6.6

Git workflow improvement CLI tool inspired by Magit
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
//! Gex configuration.
#![allow(clippy::derivable_impls)]
use std::{collections::HashMap, fs, path::PathBuf, str::FromStr, sync::OnceLock};

use anyhow::{Context, Result};
use clap::{command, Parser};
use crossterm::{event::KeyCode, style::Color};
use serde::{
    de::{self, Visitor},
    Deserialize,
};

pub static CONFIG: OnceLock<Config> = OnceLock::new();
#[macro_export]
macro_rules! config {
    () => {
        $crate::config::CONFIG
            .get()
            .expect("config wasn't initialised")
    };
}

/// Command line args.
#[derive(Parser)]
#[command(version = env!("GEX_VERSION"), about)]
pub struct Clargs {
    /// The path to the repository.
    #[clap(default_value = ".")]
    pub path: String,

    /// Path to a config file to use.
    #[clap(short, long, name = "PATH")]
    pub config_file: Option<String>,
}

/// The top-level of the config parsed from the config file.
#[derive(Deserialize, Default, Debug, PartialEq, Eq)]
#[serde(default)]
pub struct Config {
    pub options: Options,
    pub colors: Colors,
    pub keymap: Keymaps,
}

#[derive(Deserialize, Debug, PartialEq, Eq)]
#[serde(default)]
pub struct Options {
    pub auto_expand_files: bool,
    pub auto_expand_hunks: bool,
    pub editor: String,
    pub lookahead_lines: usize,
    pub sort_branches: Option<String>,
    pub truncate_lines: bool,
    pub ws_error_highlight: WsErrorHighlight,
}

impl Options {
    fn default_editor() -> String {
        git2::Config::open_default()
            .and_then(|mut config| config.snapshot())
            .and_then(|config| config.get_str("core.editor").map(|ed| ed.to_owned()))
            .unwrap_or_else(|_| std::env::var("EDITOR").unwrap_or_else(|_| "vi".to_string()))
    }
}

impl Default for Options {
    fn default() -> Self {
        Self {
            auto_expand_files: false,
            auto_expand_hunks: true,
            editor: Self::default_editor(),
            lookahead_lines: 5,
            sort_branches: None,
            truncate_lines: true,
            ws_error_highlight: WsErrorHighlight::default(),
        }
    }
}

#[derive(Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
#[serde(try_from = "String")]
pub struct WsErrorHighlight {
    pub old: bool,
    pub new: bool,
    pub context: bool,
}

#[derive(Deserialize, Debug, PartialEq, Eq)]
#[serde(default)]
pub struct Colors {
    pub foreground: Color,
    pub background: Color,
    pub heading: Color,
    pub hunk_head: Color,
    pub addition: Color,
    pub deletion: Color,
    pub key: Color,
    pub error: Color,
}

impl Default for Colors {
    fn default() -> Self {
        // We have to force colour output here regardless of NO_COLOR setting, because then we can
        // handle it ourselves. The NO_COLOR standard specifies that colour output should be
        // enabled when the user has explicitly set it, which can be achieved here by detecting the
        // env variable and then enabling color granularly based on the user config.
        crossterm::style::force_color_output(true);
        if std::env::var("NO_COLOR").is_ok_and(|v| !v.is_empty()) {
            Self {
                foreground: Color::Reset,
                background: Color::Reset,
                heading: Color::Reset,
                hunk_head: Color::Reset,
                addition: Color::Reset,
                deletion: Color::Reset,
                key: Color::Reset,
                error: Color::Reset,
            }
        } else {
            Self {
                foreground: Color::Reset,
                background: Color::Reset,
                heading: Color::Yellow,
                hunk_head: Color::Blue,
                addition: Color::DarkGreen,
                deletion: Color::DarkRed,
                key: Color::Green,
                error: Color::Red,
            }
        }
    }
}

struct KeymapsVisitor;

impl<'de> Visitor<'de> for KeymapsVisitor {
    type Value = Keymaps;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str(
            "
                        [keymap.SECTION]
                        action_under_section = ['<CHARACTER_VALUE>', \"<KeyCode enum value name>\"],
                        ...
                    ",
        )
    }

    fn visit_map<A>(self, mut map: A) -> std::result::Result<Self::Value, A::Error>
    where
        A: serde::de::MapAccess<'de>,
    {
        let mut navigation = Self::Value::default().navigation;

        while let Some((section, section_values)) =
            map.next_entry::<String, HashMap<String, Vec<String>>>()?
        {
            if section == "navigation" {
                for (action, keys) in section_values {
                    let ac: Action =
                        Deserialize::deserialize(de::value::StringDeserializer::new(action))?;

                    // over-write default key-map to action
                    navigation.retain(|_, value| value != &ac);

                    for key in keys {
                        // cross-term can't, with Serde,  directly deserialize '<CHARACTER_VALUE>' into a KeyCode
                        if key.len() == 1 {
                            if let Some(c) = key.chars().next() {
                                let key = KeyCode::Char(c);
                                navigation.insert(key, ac.clone());
                                continue;
                            }
                        }

                        let key: KeyCode =
                            Deserialize::deserialize(de::value::StringDeserializer::new(key))?;

                        navigation.insert(key, ac.clone());
                    }
                }
            }
        }

        Ok(Keymaps { navigation })
    }
}

#[derive(Debug, PartialEq, Eq)]
pub struct Keymaps {
    pub navigation: HashMap<KeyCode, Action>,
}

impl<'de> Deserialize<'de> for Keymaps {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        deserializer.deserialize_map(KeymapsVisitor)
    }
}

#[derive(Deserialize, Clone, Debug, PartialEq, Eq)]
#[serde(rename_all(deserialize = "snake_case"))]
#[cfg_attr(test, derive(strum::EnumIter))]
pub enum Action {
    MoveDown,
    MoveUp,
    NextFile,
    PreviousFile,
    ToggleExpand,
    GotoTop,
    GotoBottom,
}

impl Default for Keymaps {
    fn default() -> Self {
        Self {
            navigation: HashMap::from([
                (KeyCode::Char('j'), Action::MoveDown),
                (KeyCode::Down, Action::MoveDown),
                (KeyCode::Char('k'), Action::MoveUp),
                (KeyCode::Up, Action::MoveUp),
                (KeyCode::Char('J'), Action::NextFile),
                (KeyCode::Char('K'), Action::PreviousFile),
                (KeyCode::Char(' '), Action::ToggleExpand),
                (KeyCode::Tab, Action::ToggleExpand),
                (KeyCode::Char('g'), Action::GotoTop),
                (KeyCode::Char('G'), Action::GotoBottom),
            ]),
        }
    }
}

impl Config {
    /// Reads the config from the config file (usually `~/.config/gex/config.toml` on Linux) and
    /// returns it along with a Vec of unrecognised keys.
    /// If there is no config file, it will return `Ok(None)`.
    /// If there is a config file but it is unable to parse it, it will return `Err(_)`.
    #[allow(clippy::ref_option)]
    pub fn read_from_file(path: &Option<String>) -> Result<Option<(Self, Vec<String>)>> {
        let config_path = if let Some(path) = path {
            PathBuf::from(path)
        } else
        // First we will try where dirs tells us.
        if let Some(path) = dirs::config_dir()
            .map(|mut path| {
                path.push("gex");
                path.push("config.toml");
                path
            })
            .filter(|path| path.as_path().exists())
            // If it doesn't exist, we'll try the usual suspect. (#87)
            .or_else(|| {
                dirs::home_dir().map(|mut path| {
                    path.push(".config");
                    path.push("gex");
                    path.push("config.toml");
                    path
                })
            })
        {
            path
        } else {
            return Ok(None);
        };

        let Ok(config) = fs::read_to_string(config_path) else {
            return Ok(None);
        };

        let de = toml::Deserializer::parse(&config)?;
        let mut unused_keys = Vec::new();
        let config = serde_ignored::deserialize(de, |path| {
            unused_keys.push(path.to_string());
        })
        .context("failed to parse config file")?;
        Ok(Some((config, unused_keys)))
    }
}

impl WsErrorHighlight {
    /// The default value defined by git.
    const GIT_DEFAULT: Self = Self {
        old: false,
        new: true,
        context: false,
    };
    const NONE: Self = Self {
        old: false,
        new: false,
        context: false,
    };
    const ALL: Self = Self {
        old: true,
        new: true,
        context: true,
    };
}

impl Default for WsErrorHighlight {
    /// If none was provided by the gex config, we will look in the git config. If we couldn't get
    /// that one then we'll just provide `Self::GIT_DEFAULT`.
    fn default() -> Self {
        let Ok(git_config) = git2::Config::open_default().and_then(|mut config| config.snapshot())
        else {
            return Self::GIT_DEFAULT;
        };

        let Ok(value) = git_config.get_str("diff.wsErrorHighlight") else {
            return Self::GIT_DEFAULT;
        };

        Self::from_str(value).unwrap_or(Self::GIT_DEFAULT)
    }
}

// NOTE: If anyone is reading this, do you happen to know why this impl is even needed? Really
// feels like this should be provided by default is `FromStr` is implemented on the type.
impl TryFrom<String> for WsErrorHighlight {
    type Error = anyhow::Error;
    fn try_from(s: String) -> std::result::Result<Self, Self::Error> {
        Self::from_str(&s)
    }
}

impl FromStr for WsErrorHighlight {
    type Err = anyhow::Error;
    /// Highlight whitespace errors in the context, old or new lines of the diff. Multiple values
    /// are separated by by comma, none resets previous values, default reset the list to new and
    /// all is a shorthand for old,new,context.
    ///
    /// <https://git-scm.com/docs/git-diff#Documentation/git-diff.txt---ws-error-highlightltkindgt>
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        let mut result = Self::GIT_DEFAULT;
        for opt in s.split(',') {
            match opt {
                "all" => result = Self::ALL,
                "default" => result = Self::GIT_DEFAULT,
                "none" => result = Self::NONE,
                "old" => result.old = true,
                "new" => result.new = true,
                "context" => result.context = true,
                otherwise => {
                    return Err(anyhow::Error::msg(format!(
                        "unrecognised option in `ws_error_highlight`: {otherwise}"
                    )))
                }
            }
        }
        Ok(result)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crossterm::style::Color;
    use strum::IntoEnumIterator;

    #[test]
    fn every_action_has_a_default_key() {
        let mut action_list: Vec<Action> = Action::iter().collect();
        for (_, action) in Keymaps::default().navigation {
            action_list.retain(|x| x != &action);
        }

        assert!(
            action_list.is_empty(),
            "The following Actions do not have a default keybinding: {action_list:?}"
        );
    }

    // Should be up to date with the example config in the README.
    #[test]
    fn parse_readme_example() {
        const INPUT: &str = "
[options]
auto_expand_files = false
auto_expand_hunks = true
editor = \"nvim\"
lookahead_lines = 5
sort_branches = \"-committerdate\" # key to pass to `git branch --sort`. https://git-scm.com/docs/git-for-each-ref#_field_names 
truncate_lines = true # `false` is not recommended - see #37
ws_error_highlight = \"new\" # override git's diff.wsErrorHighlight

# Named colours use the terminal colour scheme. You can also describe your colours
# by hex string \"#RRGGBB\", RGB \"rgb_(r,g,b)\" or by Ansi \"ansi_(value)\".
#
# This example uses a Gruvbox colour theme.
[colors]
foreground = \"#ebdbb2\"
background = \"#282828\"
heading = \"#fabd2f\"
hunk_head = \"#d3869b\"
addition = \"#b8bb26\"
deletion = \"#fb4934\"
key = \"#d79921\"
error = \"#cc241d\"

[keymap.navigation]
move_down     = [\'j\', \"Down\"]
move_up       = [\'k\', \"Up\"]
next_file     = [\'J\']
previous_file = [\'K\']
toggle_expand = [\" \", \"Tab\"]
goto_top      = [\'g\']
goto_bottom   = [\'G\']
";
        assert_eq!(
            toml::from_str(INPUT),
            Ok(Config {
                options: Options {
                    auto_expand_files: false,
                    auto_expand_hunks: true,
                    editor: "nvim".to_string(),
                    lookahead_lines: 5,
                    truncate_lines: true,
                    sort_branches: Some("-committerdate".to_string()),
                    ws_error_highlight: WsErrorHighlight {
                        old: false,
                        new: true,
                        context: false
                    }
                },
                colors: Colors {
                    foreground: Color::from((235, 219, 178)),
                    background: Color::from((40, 40, 40)),
                    heading: Color::from((250, 189, 47)),
                    hunk_head: Color::from((211, 134, 155)),
                    addition: Color::from((184, 187, 38)),
                    deletion: Color::from((251, 73, 52)),
                    key: Color::from((215, 153, 33)),
                    error: Color::from((204, 36, 29))
                },
                keymap: Keymaps {
                    navigation: HashMap::from([
                        (KeyCode::Char('j'), Action::MoveDown),
                        (KeyCode::Down, Action::MoveDown),
                        (KeyCode::Char('k'), Action::MoveUp),
                        (KeyCode::Up, Action::MoveUp),
                        (KeyCode::Char('J'), Action::NextFile),
                        (KeyCode::Char('K'), Action::PreviousFile),
                        (KeyCode::Char(' '), Action::ToggleExpand),
                        (KeyCode::Tab, Action::ToggleExpand),
                        (KeyCode::Char('g'), Action::GotoTop),
                        (KeyCode::Char('G'), Action::GotoBottom),
                    ]),
                }
            })
        );
    }
}