summaryrefslogtreecommitdiffstats
path: root/src/features/navigate.rs
blob: 4e1e062a2d869e2fdea9ff15b9b255f75e9d1e40 (plain)
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
use std::io::Write;
#[cfg(target_os = "windows")]
use std::io::{Error, ErrorKind};
use std::path::PathBuf;

use crate::config::Config;
use crate::features::OptionValueFunction;

pub fn make_feature() -> Vec<(String, OptionValueFunction)> {
    builtin_feature!([
        (
            "navigate",
            bool,
            None,
            _opt => true
        ),
        (
            "file-modified-label",
            String,
            None,
            _opt => "Δ"
        )
    ])
}

// Construct the regexp used by less for paging, if --show-themes or --navigate is enabled.
pub fn make_navigate_regexp(
    show_themes: bool,
    file_modified_label: &str,
    file_added_label: &str,
    file_removed_label: &str,
    file_renamed_label: &str,
) -> String {
    if show_themes {
        "^Theme:".to_string()
    } else {
        format!(
            "^(commit|{}|{}|{}|{})",
            file_modified_label, file_added_label, file_removed_label, file_renamed_label,
        )
    }
}

// Create a less history file to be used by delta's child less process. This file is initialized
// with the contents of user's real less hist file, to which the navigate regexp is appended. This
// has the effect that 'n' or 'N' in delta's less process will search for the navigate regexp,
// without the undesirable aspects of using --pattern, yet without polluting the user's less search
// history with delta's navigate regexp. See
// https://github.com/dandavison/delta/issues/237#issuecomment-780654036. Note that with the
// current implementation, no writes to the delta less history file are propagated back to the real
// history file so, for example, a (non-navigate) search performed in the delta less process will
// not be stored in history.
pub fn copy_less_hist_file_and_append_navigate_regexp(config: &Config) -> std::io::Result<PathBuf> {
    let delta_less_hist_file = get_delta_less_hist_file()?;
    let initial_contents = ".less-history-file:\n".to_string();
    let mut contents = if let Some(hist_file) = get_less_hist_file() {
        std::fs::read_to_string(hist_file).unwrap_or(initial_contents)
    } else {
        initial_contents
    };
    if !contents.ends_with(".search\n") {
        contents = format!("{}.search\n", contents);
    }
    writeln!(
        std::fs::File::create(&delta_less_hist_file)?,
        "{}\"{}",
        contents,
        config.navigate_regexp.as_ref().unwrap(),
    )?;
    Ok(delta_less_hist_file)
}

#[cfg(target_os = "windows")]
fn get_delta_less_hist_file() -> std::io::Result<PathBuf> {
    let mut path = dirs_next::home_dir()
        .ok_or_else(|| Error::new(ErrorKind::NotFound, "Can't determine home dir"))?;
    path.push(".delta.lesshst");
    Ok(path)
}

#[cfg(not(target_os = "windows"))]
fn get_delta_less_hist_file() -> std::io::Result<PathBuf> {
    let dir = xdg::BaseDirectories::with_prefix("delta")?;
    dir.place_data_file("lesshst")
}

// LESSHISTFILE
//        Name of the history file used to remember search commands
//        and shell commands between invocations of less.  If set to
//        "-" or "/dev/null", a history file is not used.  The
//        default is "$HOME/.lesshst" on Unix systems,
//        "$HOME/_lesshst" on DOS and Windows systems, or
//        "$HOME/lesshst.ini" or "$INIT/lesshst.ini" on OS/2
//        systems.
fn get_less_hist_file() -> Option<PathBuf> {
    if let Some(home_dir) = dirs_next::home_dir() {
        match std::env::var("LESSHISTFILE").as_deref() {
            Ok("-") | Ok("/dev/null") => {
                // The user has explicitly disabled less history.
                None
            }
            Ok(path) => {
                // The user has specified a custom histfile
                Some(PathBuf::from(path))
            }
            Err(_) => {
                // The user is using the default less histfile location.
                let mut hist_file = home_dir;
                hist_file.push(if cfg!(windows) {
                    "_lesshst"
                } else {
                    ".lesshst"
                });
                Some(hist_file)
            }
        }
    } else {
        None
    }
}

#[cfg(test)]
mod tests {
    use std::fs::remove_file;

    use crate::tests::integration_test_utils;

    #[test]
    fn test_navigate_with_overriden_key_in_main_section() {
        let git_config_contents = b"
[delta]
    features = navigate
    file-modified-label = \"modified: \"
";
        let git_config_path = "delta__test_navigate_with_overriden_key_in_main_section.gitconfig";

        assert_eq!(
            integration_test_utils::make_options_from_args_and_git_config(&[], None, None)
                .file_modified_label,
            ""
        );
        assert_eq!(
            integration_test_utils::make_options_from_args_and_git_config(
                &["--features", "navigate"],
                None,
                None
            )
            .file_modified_label,
            "Δ"
        );
        assert_eq!(
            integration_test_utils::make_options_from_args_and_git_config(
                &["--navigate"],
                None,
                None
            )
            .file_modified_label,
            "Δ"
        );
        assert_eq!(
            integration_test_utils::make_options_from_args_and_git_config(
                &[],
                Some(git_config_contents),
                Some(git_config_path)
            )
            .file_modified_label,
            "modified: "
        );

        remove_file(git_config_path).unwrap();
    }

    #[test]
    fn test_navigate_with_overriden_key_in_custom_navigate_section() {
        let git_config_contents = b"
[delta]
    features = navigate

[delta \"navigate\"]
    file-modified-label = \"modified: \"
";
        let git_config_path =
            "delta__test_navigate_with_overriden_key_in_custom_navigate_section.gitconfig";

        assert_eq!(
            integration_test_utils::make_options_from_args_and_git_config(&[], None, None)
                .file_modified_label,
            ""
        );
        assert_eq!(
            integration_test_utils::make_options_from_args_and_git_config(
                &["--features", "navigate"],
                None,
                None
            )
            .file_modified_label,
            "Δ"
        );
        assert_eq!(
            integration_test_utils::make_options_from_args_and_git_config(
                &[],
                Some(git_config_contents),
                Some(git_config_path)
            )
            .file_modified_label,
            "modified: "
        );

        remove_file(git_config_path).unwrap();
    }

    #[test]
    fn test_navigate_activated_by_custom_feature() {
        let git_config_contents = b"
[delta \"my-navigate-feature\"]
    features = navigate
    file-modified-label = \"modified: \"
";
        let git_config_path = "delta__test_navigate_activated_by_custom_feature.gitconfig";

        assert_eq!(
            integration_test_utils::make_options_from_args_and_git_config(
                &[],
                Some(git_config_contents),
                Some(git_config_path)
            )
            .file_modified_label,
            ""
        );
        assert_eq!(
            integration_test_utils::make_options_from_args_and_git_config(
                &["--features", "my-navigate-feature"],
                Some(git_config_contents),
                Some(git_config_path)
            )
            .file_modified_label,
            "modified: "
        );

        remove_file(git_config_path).unwrap();
    }
}