summaryrefslogtreecommitdiffstats
path: root/src/bin/bat/main.rs
blob: 78202539da0463d122314e2d4fc06a839ffdea68 (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
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
#![deny(unsafe_code)]

mod app;
mod assets;
mod clap_app;
mod config;
mod directories;
mod input;

use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;
use std::io;
use std::io::{BufReader, Write};
use std::path::Path;
use std::process;

use nu_ansi_term::Color::Green;
use nu_ansi_term::Style;

use crate::{
    app::App,
    config::{config_file, generate_config_file},
};

#[cfg(feature = "bugreport")]
use crate::config::system_config_file;

use assets::{assets_from_cache_or_binary, clear_assets};
use directories::PROJECT_DIRS;
use globset::GlobMatcher;

use bat::{
    assets::HighlightingAssets,
    config::Config,
    controller::Controller,
    error::*,
    input::Input,
    style::{StyleComponent, StyleComponents},
    MappingTarget, PagingMode,
};

const THEME_PREVIEW_DATA: &[u8] = include_bytes!("../../../assets/theme_preview.rs");

#[cfg(feature = "build-assets")]
fn build_assets(matches: &clap::ArgMatches, config_dir: &Path, cache_dir: &Path) -> Result<()> {
    let source_dir = matches
        .get_one::<String>("source")
        .map(Path::new)
        .unwrap_or_else(|| config_dir);

    bat::assets::build(
        source_dir,
        !matches.get_flag("blank"),
        matches.get_flag("acknowledgements"),
        cache_dir,
        clap::crate_version!(),
    )
}

fn run_cache_subcommand(
    matches: &clap::ArgMatches,
    #[cfg(feature = "build-assets")] config_dir: &Path,
    default_cache_dir: &Path,
) -> Result<()> {
    let cache_dir = matches
        .get_one::<String>("target")
        .map(Path::new)
        .unwrap_or_else(|| default_cache_dir);

    if matches.get_flag("build") {
        #[cfg(feature = "build-assets")]
        build_assets(matches, config_dir, cache_dir)?;
        #[cfg(not(feature = "build-assets"))]
        println!("bat has been built without the 'build-assets' feature. The 'cache --build' option is not available.");
    } else if matches.get_flag("clear") {
        clear_assets(cache_dir);
    }

    Ok(())
}

fn get_syntax_mapping_to_paths<'r, 't, I>(mappings: I) -> HashMap<&'t str, Vec<String>>
where
    I: IntoIterator<Item = (&'r GlobMatcher, &'r MappingTarget<'t>)>,
    't: 'r, // target text outlives rule
{
    let mut map = HashMap::new();
    for mapping in mappings {
        if let (matcher, MappingTarget::MapTo(s)) = mapping {
            let globs = map.entry(*s).or_insert_with(Vec::new);
            globs.push(matcher.glob().glob().into());
        }
    }
    map
}

pub fn get_languages(config: &Config, cache_dir: &Path) -> Result<String> {
    let mut result: String = String::new();

    let assets = assets_from_cache_or_binary(config.use_custom_assets, cache_dir)?;
    let mut languages = assets
        .get_syntaxes()?
        .iter()
        .filter(|syntax| !syntax.hidden && !syntax.file_extensions.is_empty())
        .cloned()
        .collect::<Vec<_>>();

    // Handling of file-extension conflicts, see issue #1076
    for lang in &mut languages {
        let lang_name = lang.name.clone();
        lang.file_extensions.retain(|extension| {
            // The 'extension' variable is not certainly a real extension.
            //
            // Skip if 'extension' starts with '.', likely a hidden file like '.vimrc'
            // Also skip if the 'extension' contains another real extension, likely
            // that is a full match file name like 'CMakeLists.txt' and 'Cargo.lock'
            if extension.starts_with('.') || Path::new(extension).extension().is_some() {
                return true;
            }

            let test_file = Path::new("test").with_extension(extension);
            let syntax_in_set = assets.get_syntax_for_path(test_file, &config.syntax_mapping);
            matches!(syntax_in_set, Ok(syntax_in_set) if syntax_in_set.syntax.name == lang_name)
        });
    }

    languages.sort_by_key(|lang| lang.name.to_uppercase());

    let configured_languages = get_syntax_mapping_to_paths(config.syntax_mapping.all_mappings());

    for lang in &mut languages {
        if let Some(additional_paths) = configured_languages.get(lang.name.as_str()) {
            lang.file_extensions
                .extend(additional_paths.iter().cloned());
        }
    }

    if config.loop_through {
        for lang in languages {
            writeln!(result, "{}:{}", lang.name, lang.file_extensions.join(",")).ok();
        }
    } else {
        let longest = languages
            .iter()
            .map(|syntax| syntax.name.len())
            .max()
            .unwrap_or(32); // Fallback width if they have no language definitions.

        let comma_separator = ", ";
        let separator = " ";
        // Line-wrapping for the possible file extension overflow.
        let desired_width = config.term_width - longest - separator.len();

        let style = if config.colored_output {
            Green.normal()
        } else {
            Style::default()
        };

        for lang in languages {
            write!(result, "{:width$}{}", lang.name, separator, width = longest).ok();

            // Number of characters on this line so far, wrap before `desired_width`
            let mut num_chars = 0;

            let mut extension = lang.file_extensions.iter().peekable();
            while let Some(word) = extension.next() {
                // If we can't fit this word in, then create a line break and align it in.
                let new_chars = word.len() + comma_separator.len();
                if num_chars + new_chars >= desired_width {
                    num_chars = 0;
                    write!(result, "\n{:width$}{}", "", separator, width = longest).ok();
                }

                num_chars += new_chars;
                write!(result, "{}", style.paint(&word[..])).ok();
                if extension.peek().is_some() {
                    result += comma_separator;
                }
            }
            result += "\n";
        }
    }

    Ok(result)
}

fn theme_preview_file<'a>() -> Input<'a> {
    Input::from_reader(Box::new(BufReader::new(THEME_PREVIEW_DATA)))
}

pub fn list_themes(cfg: &Config, config_dir: &Path, cache_dir: &Path) -> Result<()> {
    let assets = assets_from_cache_or_binary(cfg.use_custom_assets, cache_dir)?;
    let mut config = cfg.clone();
    let mut style = HashSet::new();
    style.insert(StyleComponent::Plain);
    config.language = Some("Rust");
    config.style_components = StyleComponents(style);

    let stdout = io::stdout();
    let mut stdout = stdout.lock();

    if config.colored_output {
        let default_theme = HighlightingAssets::default_theme();
        for theme in assets.themes() {
            let default_theme_info = if default_theme == theme {
                " (default)"
            } else {
                ""
            };
            writeln!(
                stdout,
                "Theme: {}{}\n",
                Style::new().bold().paint(theme.to_string()),
                default_theme_info
            )?;
            config.theme = theme.to_string();
            Controller::new(&config, &assets)
                .