summaryrefslogtreecommitdiffstats
path: root/src/context/mod.rs
blob: 21472ac45e386dea365db2bbff5403a9f2584e0a (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
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
use super::disk_usage::{file_size::DiskUsage, units::PrefixKind};
use crate::tty;
use clap::{parser::ValueSource, ArgMatches, CommandFactory, FromArgMatches, Parser};
use color::Coloring;
use error::Error;
use ignore::{
    overrides::{Override, OverrideBuilder},
    DirEntry,
};
use regex::Regex;
use std::{
    borrow::Borrow,
    convert::From,
    ffi::{OsStr, OsString},
    num::NonZeroUsize,
    path::{Path, PathBuf},
    thread::available_parallelism,
};

/// Operations to load in defaults from configuration file.
pub mod config;

/// Controlling color of output.
pub mod color;

/// Controlling order of directories in output.
pub mod dir;

/// [Context] related errors.
pub mod error;

/// Common cross-platform file-types.
pub mod file;

/// For determining the output layout.
pub mod layout;

/// Utilities to print output.
pub mod column;

/// Printing order kinds.
pub mod sort;

/// Different types of timestamps available in long view.
#[cfg(unix)]
pub mod time;

/// Defines the CLI.
#[derive(Parser, Debug)]
#[command(name = "erdtree")]
#[command(author = "Benjamin Nguyen. <benjamin.van.nguyen@gmail.com>")]
#[command(version = "3.0.2")]
#[command(about = "erdtree (erd) is a cross-platform, multi-threaded, and general purpose filesystem and disk usage utility.", long_about = None)]
pub struct Context {
    /// Directory to traverse; defaults to current working directory
    dir: Option<PathBuf>,

    /// Use configuration of named table rather than the top-level table in .erdtree.toml
    #[arg(short = 'c', long)]
    pub config: Option<String>,

    /// Mode of coloring output
    #[arg(short = 'C', long, value_enum, default_value_t)]
    pub color: Coloring,

    /// Print physical or logical file size
    #[arg(short, long, value_enum, default_value_t)]
    pub disk_usage: DiskUsage,

    /// Follow symlinks
    #[arg(short = 'f', long)]
    pub follow: bool,

    /// Print disk usage in human-readable format
    #[arg(short = 'H', long)]
    pub human: bool,

    /// Do not respect .gitignore files
    #[arg(short = 'i', long)]
    pub no_ignore: bool,

    /// Display file icons
    #[arg(short = 'I', long)]
    pub icons: bool,

    /// Show extended metadata and attributes
    #[cfg(unix)]
    #[arg(short, long)]
    pub long: bool,

    /// Show file's groups
    #[cfg(unix)]
    #[arg(long)]
    pub group: bool,

    /// Show each file's ino
    #[cfg(unix)]
    #[arg(long)]
    pub ino: bool,

    /// Show the total number of hardlinks to the underlying inode
    #[cfg(unix)]
    #[arg(long)]
    pub nlink: bool,

    /// Show permissions in numeric octal format instead of symbolic
    #[cfg(unix)]
    #[arg(long, requires = "long")]
    pub octal: bool,

    /// Which kind of timestamp to use; modified by default
    #[cfg(unix)]
    #[arg(long, value_enum, requires = "long")]
    pub time: Option<time::Stamp>,

    /// Which format to use for the timestamp; default by default
    #[cfg(unix)]
    #[arg(long = "time-format", value_enum, requires = "long")]
    pub time_format: Option<time::Format>,

    /// Maximum depth to display
    #[arg(short = 'L', long, value_name = "NUM")]
    level: Option<usize>,

    /// Regular expression (or glob if '--glob' or '--iglob' is used) used to match files
    #[arg(short, long)]
    pub pattern: Option<String>,

    /// Enables glob based searching
    #[arg(group = "searching", long, requires = "pattern")]
    pub glob: bool,

    /// Enables case-insensitive glob based searching
    #[arg(group = "searching", long, requires = "pattern")]
    pub iglob: bool,

    /// Restrict regex or glob search to a particular file-type
    #[arg(short = 't', long, requires = "pattern", value_enum)]
    pub file_type: Option<file::Type>,

    /// Remove empty directories from output
    #[arg(short = 'P', long)]
    pub prune: bool,

    /// How to sort entries
    #[arg(short, long, value_enum, default_value_t)]
    pub sort: sort::Type,

    /// Sort directories before or after all other file types
    #[arg(long, value_enum, default_value_t)]
    pub dir_order: dir::Order,

    /// Number of threads to use
    #[arg(short = 'T', long, default_value_t = Context::num_threads())]
    pub threads: usize,

    /// Report disk usage in binary or SI units
    #[arg(short, long, value_enum, default_value_t)]
    pub unit: PrefixKind,

    /// Prevent traversal into directories that are on different filesystems
    #[arg(short = 'x', long = "one-file-system")]
    pub same_fs: bool,

    /// Which kind of layout to use when rendering the output
    #[arg(short = 'y', long, value_enum, default_value_t)]
    pub layout: layout::Type,

    /// Show hidden files
    #[arg(short = '.', long)]
    pub hidden: bool,

    /// Disable traversal of .git directory when traversing hidden files
    #[arg(long, requires = "hidden")]
    pub no_git: bool,

    #[arg(long)]
    /// Print completions for a given shell to stdout
    pub completions: Option<clap_complete::Shell>,

    /// Only print directories
    #[arg(long)]
    pub dirs_only: bool,

    /// Don't read configuration file
    #[arg(long)]
    pub no_config: bool,

    /// Hides the progress indicator
    #[arg(long)]
    pub no_progress: bool,

    /// Omit disk usage from output
    #[arg(long)]
    pub suppress_size: bool,

    /// Truncate output to fit terminal emulator window
    #[arg(long)]
    pub truncate: bool,

    //////////////////////////
    /* INTERNAL USAGE BELOW */
    //////////////////////////
    /// Is stdin in a tty?
    #[clap(skip = tty::stdin_is_tty())]
    pub stdin_is_tty: bool,

    /// Is stdin in a tty?
    #[clap(skip = tty::stdout_is_tty())]
    pub stdout_is_tty: bool,

    /// Restricts column width of size not including units
    #[clap(skip = usize::default())]
    pub max_size_width: usize,

    /// Restricts column width of disk_usage units
    #[clap(skip = usize::default())]
    pub max_size_unit_width: usize,

    /// Restricts column width of nlink for long view
    #[clap(skip = usize::default())]
    #[cfg(unix)]
    pub max_nlink_width: usize,

    /// Restricts column width of ino for long view
    #[clap(skip = usize::default())]
    #[cfg(unix)]
    pub max_ino_width: usize,

    /// Restricts column width of block for long view
    #[clap(skip = usize::default())]
    #[cfg(unix)]
    pub max_block_width: usize,

    /// Restricts column width of file owner for long view
    #[clap(skip = usize::default())]
    #[cfg(unix)]
    pub max_owner_width: usize,

    /// Restricts column width of file group for long view
    #[clap(skip = usize::default())]
    #[cfg(unix)]
    pub max_group_width: usize,

    /// Width of the terminal emulator's window
    #[clap(skip)]
    pub window_width: Option<usize>,
}

type Predicate = Result<Box<dyn Fn(&DirEntry) -> bool + Send + Sync + 'static>, Error>;

impl Context {
    /// Initializes [Context], optionally reading in the configuration file to override defaults.
    /// Arguments provided will take precedence over config.
    pub fn try_init() -> Result<Self, Error> {
        // User-provided arguments from command-line.
        let user_args = Self::command().args_override_self(true).get_matches();

        // User provides `--no-config`.
        if user_args.get_one::<bool>("no_config").is_some_and(|b| *b) {
            return Self::from_arg_matches(&user_args).map_err(Error::ArgParse);
        }

        // Load in `.erdtreerc` or `.erdtree.toml`.
        let config_args = if let Some(config) = config::rc::read_config_to_string() {
            let raw_args = config::rc::parse(&config);

            Self::command().get_matches_from(raw_args)
        } else if let Ok(config) = config::toml::load() {
            let named_table = user_args.get_one::<String>("config");
            let raw_args = config::toml::parse(config, named_table.map(String::as_str))?;

            Self::command().get_matches_from(raw_args)
        } else {
            return Self::from_arg_matches(&user_args).map_err(Error::ArgParse);
        };

        // If the user did not provide any arguments just read from config.
        if !user_args.args_present() {
            return Self::from_arg_matches(&config_args).map_err(Error::Config);
        }

        let mut args = vec![OsString::from("--")];

        let ids = Self::command()
            .get_arguments()
            .map(|arg| arg.get_id().clone())
            .collect::<Vec<_>>();

        for id in ids {
            let id_str = id.as_str();

            if id_str == "dir" {
                if let Ok(Some(dir)) = user_args.try_get_one::<PathBuf>(id_str) {
                    args.push(dir.as_os_str().to_owned());
                    continue;
                }
            }

            let Some(source) = user_args.value_source(id_str) else {
                if let Some(params) = Self::extract_args_from(id_str, &config_args) {
                    args.extend(params);