colorls 1.0.11

A fast, production-ready Rust rewrite of colorls: a beautified ls with icons, colors, git status and tree view.
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
//! File: src\main.rs
//! Author: Hadi Cahyadi <cumulus13@gmail.com>
//! Date: 2026-08-20
//! Description:
//! License: MIT

mod cli;
mod colors;
mod config;
mod entry;
mod git;
mod icons;
mod render;
mod sorter;
mod theme;
mod util;

use std::path::{Path, PathBuf};
use std::process::ExitCode;

use anyhow::{Context, Result};
use clap::{CommandFactory, FromArgMatches};
use clap_version_flag::colorful_version;
use cli::{Cli, ColorWhen};
use entry::{read_dir_entries, FileEntry};
use git::{git_available, status_for_dir, GitRepoInfo};
use render::RenderCtx;
use theme::{init_config_dir, Theme};
use util::PROG_NAME;

/// Parse CLI args with the `Command`'s name/bin_name set to whichever
/// executable name we were actually invoked as (`colorls` or `lls`), so
/// `--help` and `--version` reflect that instead of always saying
/// "colorls" regardless of how the user launched it.
fn parse_cli() -> Cli {
    let name = PROG_NAME.as_str();
    let cmd = Cli::command().name(name).bin_name(name);
    let matches = cmd.get_matches();
    match Cli::from_arg_matches(&matches) {
        Ok(cli) => cli,
        Err(e) => e.exit(),
    }
}

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().collect();
    if args.len() == 2 && (args[1] == "-V" || args[1] == "--version") {
        let version = colorful_version!();
        version.print_and_exit();
    }

    #[cfg(windows)]
    {
        let _ = colored::control::set_virtual_terminal(true);
    }

    let mut cli = parse_cli();
    let pager = setup_pager(&mut cli);

    let result = run(cli);

    // Close the pipe into the pager (sends it EOF) before waiting on it —
    // otherwise it hangs forever expecting more input. If no pager was
    // spawned this is a harmless no-op.
    util::close_output();
    if let Some(mut child) = pager {
        let _ = child.wait();
    }

    match result {
        Ok(code) => code,
        Err(e) => {
            eprintln!("{}: error: {:#}", PROG_NAME.as_str(), e);
            ExitCode::FAILURE
        }
    }
}

/// Once a pager is spawned, output is headed into its stdin pipe rather
/// than the terminal directly — so plain TTY auto-detection on our own
/// stdout would (correctly, in isolation) conclude "not a terminal, no
/// color". Upgrade `Auto` to `Always` to counter that, since the whole
/// point of `--paginate` is to preserve color through the pager. An
/// explicit `--color=never` is a deliberate choice and always wins.
fn color_for_pager(current: ColorWhen) -> ColorWhen {
    if current == ColorWhen::Never {
        current
    } else {
        ColorWhen::Always
    }
}

/// If `--paginate`/`-p` was requested, spawn a pager (`$PAGER`, or
/// `less -R` if that's unset) with its stdin piped, and redirect all
/// subsequent `oprintln!` output into that pipe instead of real stdout
/// (see `util::init_output_writer`). Also upgrades `cli.color` to
/// `Always` unless the user explicitly said `--color=never`, since once
/// output is headed into a pager rather than the terminal directly, plain
/// TTY auto-detection on our own stdout would (correctly, in isolation)
/// conclude "not a terminal, no color" — exactly the "color disappears
/// when piped" behavior this flag exists to fix.
///
/// Returns `None` — leaving output on real stdout, with `cli.color`
/// untouched — both when paginate wasn't requested, and when it was but
/// no usable pager could be launched (e.g. `less` isn't on PATH, common on
/// a bare Windows install); the latter prints a one-line warning and
/// degrades to plain unpaginated output rather than risking a pager that
/// can't interpret ANSI codes turning colored output into visible escape-
/// sequence garbage.
fn setup_pager(cli: &mut Cli) -> Option<std::process::Child> {
    if !cli.paginate {
        return None;
    }

    let pager_cmd = std::env::var("PAGER").unwrap_or_else(|_| "less -R".to_string());
    let mut parts = pager_cmd.split_whitespace();
    let prog = parts.next()?;
    let args: Vec<&str> = parts.collect();

    match std::process::Command::new(prog)
        .args(&args)
        .stdin(std::process::Stdio::piped())
        .spawn()
    {
        Ok(mut child) => {
            let stdin = child.stdin.take()?;
            util::init_output_writer(Box::new(stdin));
            cli.color = color_for_pager(cli.color);
            Some(child)
        }
        Err(e) => {
            eprintln!(
                "{}: warning: couldn't launch pager `{}` ({}); printing directly instead",
                PROG_NAME.as_str(),
                pager_cmd,
                e
            );
            None
        }
    }
}

fn run(mut cli: Cli) -> Result<ExitCode> {
    let resolved = config::load(cli.config_path.as_deref())?;

    if cli.print_config_dir {
        match &resolved.dir {
            Some(d) => crate::oprintln!("{}", d.display()),
            None => crate::oprintln!("(no config directory could be resolved on this platform)"),
        }
        return Ok(ExitCode::SUCCESS);
    }

    if cli.init_config {
        let dir = resolved
            .dir
            .clone()
            .context("could not resolve a config directory on this platform")?;
        let written = init_config_dir(&dir)?;
        if written.is_empty() {
            crate::oprintln!(
                "{}: config already present at {} (nothing overwritten)",
                PROG_NAME.as_str(),
                dir.display()
            );
        } else {
            crate::oprintln!(
                "{}: wrote default config to {}",
                PROG_NAME.as_str(),
                dir.display()
            );
            for f in written {
                crate::oprintln!("  {}", f);
            }
        }
        return Ok(ExitCode::SUCCESS);
    }

    // Layer config.yaml settings under any flags the user didn't explicitly
    // pass, so CLI flags always win.
    let settings = resolved.settings.clone();
    if !cli.light && !cli.dark {
        if let Some(theme_name) = &settings.theme {
            if theme_name.eq_ignore_ascii_case("light") {
                cli.light = true;
            }
        }
    }
    if !cli.git_status {
        cli.git_status = settings.git_status.unwrap_or(false);
    }
    if !cli.group_directories_first {
        cli.group_directories_first = settings.group_directories_first.unwrap_or(false);
    }
    if !cli.sort_files_first {
        cli.sort_files_first = settings.sort_files_first.unwrap_or(false);
    }
    if !cli.report {
        cli.report = settings.report.unwrap_or(false);
    }
    if !cli.all && !cli.almost_all && settings.all.unwrap_or(false) {
        cli.all = true;
    }
    if !cli.long {
        cli.long = settings.long.unwrap_or(false);
    }
    if let Some(depth) = cli.tree {
        // `0` is clap's sentinel for "bare `--tree` with no explicit
        // depth" (see cli.rs) — resolve it against config.yaml's
        // `tree_depth`, falling back to 3 if that's unset too. An
        // explicit `--tree=N` from the user always wins outright.
        if depth == 0 {
            cli.tree = Some(settings.tree_depth.unwrap_or(3).max(1));
        }
    }

    let icons_enabled = if cli.no_icons {
        false
    } else if cli.icons {
        true
    } else {
        settings.icons.unwrap_or(true)
    };

    let color_enabled = match cli.color {
        ColorWhen::Always => true,
        ColorWhen::Never => false,
        ColorWhen::Auto => {
            use std::io::IsTerminal;
            std::io::stdout().is_terminal()
        }
    };

    // `colored` auto-detects TTY-ness internally and will otherwise ignore
    // our own --color=always/never decision when stdout is piped (e.g. into
    // `head` or a file); force it to always respect our resolved choice.
    colored::control::set_override(color_enabled);

    let theme = Theme::load(resolved.dir.as_deref(), cli.light)
        .context("failed to load color/icon theme")?;

    let paths: Vec<PathBuf> = if cli.paths.is_empty() {
        vec![PathBuf::from(".")]
    } else {
        cli.paths.clone()
    };

    let mut any_error = false;
    let show_headers = paths.len() > 1;

    for (idx, path) in paths.iter().enumerate() {
        if idx > 0 {
            crate::oprintln!();
        }
        if let Err(e) = list_one(
            path,
            &cli,
            &theme,
            color_enabled,
            icons_enabled,
            show_headers,
        ) {
            eprintln!("{}: {}: {:#}", PROG_NAME.as_str(), path.display(), e);
            any_error = true;
        }
    }

    if any_error {
        Ok(ExitCode::FAILURE)
    } else {
        Ok(ExitCode::SUCCESS)
    }
}

fn list_one(
    path: &Path,
    cli: &Cli,
    theme: &Theme,
    color_enabled: bool,
    icons_enabled: bool,
    show_headers: bool,
) -> Result<()> {
    if !path.exists() {
        anyhow::bail!("no such file or directory");
    }

    let git_available_flag = if cli.git_status {
        let avail = git_available();
        if !avail && !cli.quiet {
            eprintln!(
                "{}: warning: `git` executable not found; --gs disabled",
                PROG_NAME.as_str()
            );
        }
        avail
    } else {
        false
    };

    let git_info: Option<GitRepoInfo> = if git_available_flag {
        let target_dir = if path.is_dir() {
            path
        } else {
            path.parent().unwrap_or_else(|| Path::new("."))
        };
        status_for_dir(target_dir)
    } else {
        None
    };

    let ctx = RenderCtx {
        cli,
        theme,
        color_enabled,
        icons_enabled,
        git: git_info.as_ref(),
    };

    if let Some(info) = &git_info {
        if let Some(branch) = &info.branch {
            let text = if icons_enabled {
                format!("\u{e0a0} {}", branch)
            } else {
                branch.clone()
            };
            let label = crate::colors::paint(&text, "git_branch", theme, color_enabled);
            crate::oprintln!("{}", label);
        }
    }

    if path.is_file() {
        if show_headers {
            crate::oprintln!("{}:", path.display());
        }
        let entry = FileEntry::from_path(path).with_context(|| "reading metadata")?;
        if cli.long {
            render::long::render(std::slice::from_ref(&entry), &ctx);
        } else {
            render::grid::render(std::slice::from_ref(&entry), &ctx);
        }
        return Ok(());
    }

    if show_headers {
        crate::oprintln!("{}:", path.display());
    }

    if cli.tree.is_some() {
        render::tree::render(path, cli, &ctx, git_info.as_ref());
        return Ok(());
    }

    if cli.recursive {
        list_dir_recursive(path, cli, &ctx, theme, color_enabled, true)?;
        return Ok(());
    }

    let entries = list_dir_flat(path, cli)?;

    if cli.long {
        render::long::render(&entries, &ctx);
    } else {
        render::grid::render(&entries, &ctx);
    }

    if cli.report {
        print_report(&entries, theme, color_enabled);
    }

    Ok(())
}

/// Read, filter, sort, and (for `-a`) prepend `.`/`..` for a single
/// directory. Shared by the flat and recursive (`-R`) listing paths.
fn list_dir_flat(path: &Path, cli: &Cli) -> Result<Vec<FileEntry>> {
    let mut entries =
        read_dir_entries(path).with_context(|| format!("reading directory {}", path.display()))?;

    if !cli.show_hidden() {
        entries.retain(|e| !e.is_hidden());
    }

    sorter::sort_entries(&mut entries, cli);

    if cli.include_dot_entries() {
        if let Ok(dots) = entry::dot_entries(path) {
            let mut out = dots.to_vec();
            out.extend(entries);
            entries = out;
        }
    }

    Ok(entries)
}

/// `ls -R`-style recursive flat listing: print each directory's contents,
/// then recurse into every real (non `.`/`..`, non-symlink) subdirectory
/// with a `path:` header, depth-first.
fn list_dir_recursive(
    path: &Path,
    cli: &Cli,
    ctx: &RenderCtx,
    theme: &Theme,
    color_enabled: bool,
    is_first: bool,
) -> Result<()> {
    if !is_first {
        crate::oprintln!();
        crate::oprintln!("{}:", path.display());
    }

    let entries = list_dir_flat(path, cli)?;

    if cli.long {
        render::long::render(&entries, ctx);
    } else {
        render::grid::render(&entries, ctx);
    }

    if cli.report {
        print_report(&entries, theme, color_enabled);
    }

    let mut subdirs: Vec<PathBuf> = entries
        .iter()
        .filter(|e| e.is_dir && !e.is_symlink && e.name != "." && e.name != "..")
        .map(|e| e.path.clone())
        .collect();
    subdirs.sort();

    for sub in subdirs {
        list_dir_recursive(&sub, cli, ctx, theme, color_enabled, false)?;
    }

    Ok(())
}

fn print_report(entries: &[FileEntry], theme: &Theme, color_enabled: bool) {
    let dirs = entries.iter().filter(|e| e.is_dir).count();
    let files = entries.len() - dirs;
    let total_size: u64 = entries.iter().filter(|e| !e.is_dir).map(|e| e.size).sum();

    let line = format!(
        "\n{} directories, {} files, {} total",
        dirs,
        files,
        util::human_size(total_size)
    );
    crate::oprintln!(
        "{}",
        crate::colors::paint(&line, "report", theme, color_enabled)
    );
}

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

    #[test]
    fn auto_upgrades_to_always_for_pager() {
        assert_eq!(color_for_pager(ColorWhen::Auto), ColorWhen::Always);
    }

    #[test]
    fn always_stays_always_for_pager() {
        assert_eq!(color_for_pager(ColorWhen::Always), ColorWhen::Always);
    }

    #[test]
    fn explicit_never_is_preserved_for_pager() {
        // The one case that must NOT be overridden: the user explicitly
        // opted out of color, even while paginating.
        assert_eq!(color_for_pager(ColorWhen::Never), ColorWhen::Never);
    }
}