Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/lsd.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ lsd is a ls command with a lot of pretty colours and some other stuff to enrich
: Natural sort of (version) numbers within text

`--blocks <blocks>...`
: Specify the blocks that will be displayed and in what order [possible values: permission, user, group, size, date, name, inode, git]
: Specify the blocks that will be displayed and in what order [possible values: permission, user, group, size, date, name, inode, links, lines, git]

`--color <color>...`
: When to use terminal colours [default: auto] [possible values: always, auto, never]
Expand Down
2 changes: 1 addition & 1 deletion doc/samples/config-sample.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ classic: false
# == Blocks ==
# This specifies the columns and their order when using the long and the tree
# layout.
# Possible values: permission, user, group, context, size, date, name, inode, links, git
# Possible values: permission, user, group, context, size, date, name, inode, links, lines, git
blocks:
- permission
- user
Expand Down
2 changes: 1 addition & 1 deletion src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ pub struct Cli {
#[arg(
long,
value_delimiter = ',',
value_parser = ["permission", "user", "group", "context", "size", "date", "name", "inode", "links", "git"],
value_parser = ["permission", "user", "group", "context", "size", "date", "name", "inode", "links", "lines", "lines_value", "git"],
)]
pub blocks: Vec<String>,

Expand Down
7 changes: 7 additions & 0 deletions src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,13 @@ impl Core {
}
}

// Only calculate the total lines of a directory if it will be displayed
if self.flags.total_size.0 && self.flags.blocks.displays_lines() {
for meta in &mut meta_list.iter_mut() {
meta.calculate_total_lines();
}
}

(meta_list, exit_code)
}

Expand Down
57 changes: 57 additions & 0 deletions src/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,31 @@ fn get_output(
Some(links) => links.render(colors),
None => colorize_missing("?"),
}),
Block::Lines => {
let pad = if Layout::Tree == flags.layout && 0 == tree.0 && 0 == i {
None
} else {
Some(padding_rules.get(&Block::LinesValue).copied().unwrap_or(0))
};
block_vec.push(match &meta.lines {
Some(lines) => {
let value_str = lines.value_string();
let rendered = lines.render(colors);
if let Some(align) = pad {
let left_pad = " ".repeat(align.saturating_sub(value_str.len()));
let padded = format!("{}{}", left_pad, rendered);
colors.colorize(padded, &Elem::FileSmall)
} else {
rendered
}
}
None => colorize_missing("?"),
})
}
Block::LinesValue => block_vec.push(match &meta.lines {
Some(lines) => lines.render(colors),
None => colorize_missing("?"),
}),
Block::Permission => {
block_vec.extend([
meta.file_type.render(colors),
Expand Down Expand Up @@ -486,6 +511,32 @@ fn detect_size_lengths(metas: &[Meta], flags: &Flags) -> usize {
max_value_length
}

fn detect_lines_lengths(metas: &[Meta], flags: &Flags) -> usize {
let mut max_value_length: usize = 0;

for meta in metas {
let value_len = match &meta.lines {
Some(lines) => lines.value_string().len(),
None => 1, // "-" character
};

if value_len > max_value_length {
max_value_length = value_len;
}

if Layout::Tree == flags.layout {
if let Some(subs) = &meta.content {
let sub_length = detect_lines_lengths(subs, flags);
if sub_length > max_value_length {
max_value_length = sub_length;
}
}
}
}

max_value_length
}

fn get_padding_rules(metas: &[Meta], flags: &Flags) -> HashMap<Block, usize> {
let mut padding_rules: HashMap<Block, usize> = HashMap::new();

Expand All @@ -495,6 +546,12 @@ fn get_padding_rules(metas: &[Meta], flags: &Flags) -> HashMap<Block, usize> {
padding_rules.insert(Block::SizeValue, size_val);
}

if flags.blocks.0.contains(&Block::Lines) {
let lines_val = detect_lines_lengths(metas, flags);

padding_rules.insert(Block::LinesValue, lines_val);
}

padding_rules
}

Expand Down
23 changes: 23 additions & 0 deletions src/flags/blocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ impl Blocks {
self.0.contains(&Block::Size)
}

/// Checks whether `self` contains a [Block] of variant [Lines](Block::Lines).
pub fn displays_lines(&self) -> bool {
self.0.contains(&Block::Lines)
}

/// Inserts a [Block] of variant [INode](Block::Context), if `self` does not already contain a
/// [Block] of that variant. The positioning will be best-effort approximation of coreutils
/// ls position for a security context
Expand Down Expand Up @@ -194,6 +199,8 @@ pub enum Block {
Name,
INode,
Links,
Lines,
LinesValue,
GitStatus,
}

Expand All @@ -202,6 +209,8 @@ impl Block {
match self {
Block::INode => "INode",
Block::Links => "Links",
Block::Lines => "Lines",
Block::LinesValue => "LinesValue",
Block::Permission => "Permissions",
Block::User => "User",
Block::Group => "Group",
Expand Down Expand Up @@ -230,6 +239,8 @@ impl TryFrom<&str> for Block {
"name" => Ok(Self::Name),
"inode" => Ok(Self::INode),
"links" => Ok(Self::Links),
"lines" => Ok(Self::Lines),
"lines_value" => Ok(Self::LinesValue),
"git" => Ok(Self::GitStatus),
_ => Err(format!("Not a valid block name: {string}")),
}
Expand Down Expand Up @@ -582,10 +593,22 @@ mod test_block {
assert_eq!(Ok(Block::Context), Block::try_from("context"));
}

#[test]
fn test_lines() {
assert_eq!(Ok(Block::Lines), Block::try_from("lines"));
}

#[test]
fn test_lines_value() {
assert_eq!(Ok(Block::LinesValue), Block::try_from("lines_value"));
}

#[test]
fn test_block_headers() {
assert_eq!(Block::INode.get_header(), "INode");
assert_eq!(Block::Links.get_header(), "Links");
assert_eq!(Block::Lines.get_header(), "Lines");
assert_eq!(Block::LinesValue.get_header(), "LinesValue");
assert_eq!(Block::Permission.get_header(), "Permissions");
assert_eq!(Block::User.get_header(), "User");
assert_eq!(Block::Group.get_header(), "Group");
Expand Down
185 changes: 185 additions & 0 deletions src/meta/lines.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
use crate::color::{ColoredString, Colors, Elem};
use std::fs::{File, Metadata};
use std::io::{BufRead, BufReader, Read};
use std::path::Path;

/// Maximum file size to scan for line counting (10MB).
/// Files larger than this will not have their lines counted to avoid performance issues.
const MAX_FILE_SIZE: u64 = 10 * 1024 * 1024;

/// Size of buffer to check for binary files (8KB).
/// We check this many bytes at the start of a file for null bytes to detect binary files.
const BINARY_CHECK_SIZE: usize = 8192;

/// Represents the line count of a file.
///
/// For regular text files, contains Some(count). For directories, binary files,
/// files that are too large, or files that cannot be read, contains None.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub struct Lines {
count: Option<u64>,
}

impl Lines {
/// Create a Lines instance from a total count.
///
/// This is used when calculating total lines for directories,
/// where we sum up the line counts of all contained files.
pub fn from_total(count: u64) -> Self {
Self { count: Some(count) }
}

/// Create a Lines instance by counting lines in a file.
///
/// Returns None for:
/// - Directories and non-regular files
/// - Files larger than MAX_FILE_SIZE
/// - Binary files (detected by null bytes)
/// - Files that cannot be read
pub fn from_path(path: &Path, metadata: &Metadata) -> Self {
// Only count lines for regular files
if !metadata.is_file() {
return Self { count: None };
}

// Skip files that are too large to avoid performance issues
if metadata.len() > MAX_FILE_SIZE {
return Self { count: None };
}

// Attempt to count lines, returning None on any error
match Self::count_lines(path) {
Ok(count) => Self { count: Some(count) },
Err(_) => Self { count: None },
}
}

/// Count the number of lines in a file.
///
/// Returns 0 for binary files (detected by null bytes in first 8KB).
/// Returns the actual line count for text files.
fn count_lines(path: &Path) -> std::io::Result<u64> {
let file = File::open(path)?;
let mut reader = BufReader::new(file);

// Check if file is binary by scanning for null bytes
let mut buffer = vec![0; BINARY_CHECK_SIZE];
let bytes_read = reader.read(&mut buffer)?;

// Binary files contain null bytes - return 0 to indicate this
if buffer[..bytes_read].contains(&0) {
return Ok(0);
}

// Reopen file to count lines from the beginning
drop(reader);
let file = File::open(path)?;
let reader = BufReader::new(file);

// Count lines using BufReader's lines iterator
let mut count = 0u64;
for _ in reader.lines() {
count += 1;
}

Ok(count)
}

/// Render the line count with appropriate coloring.
///
/// Uses file size color scheme:
/// - Small files (<100 lines): FileSmall color
/// - Medium files (100-999 lines): FileMedium color
/// - Large files (>=1000 lines): FileLarge color
/// - Binary/unreadable files: NoAccess color (displays "-")
pub fn render(&self, colors: &Colors) -> ColoredString {
match self.count {
Some(0) => colors.colorize('-', &Elem::NoAccess),
Some(c) => {
let elem = if c >= 1000 {
&Elem::FileLarge
} else if c >= 100 {
&Elem::FileMedium
} else {
&Elem::FileSmall
};
colors.colorize(c.to_string(), elem)
}
None => colors.colorize('-', &Elem::NoAccess),
}
}

/// Get the line count as a string for alignment calculations.
///
/// Returns "-" for binary files, directories, and unreadable files.
pub fn value_string(&self) -> String {
match self.count {
Some(0) => String::from("-"),
Some(c) => c.to_string(),
None => String::from("-"),
}
}
}

#[cfg(test)]
mod tests {
use super::Lines;
use std::io::Write;
use tempfile::NamedTempFile;

#[test]
fn test_lines_empty_file() {
let file = NamedTempFile::new().unwrap();
let meta = file.path().metadata().unwrap();
let lines = Lines::from_path(file.path(), &meta);
assert_eq!(lines.count, Some(0));
}

#[test]
fn test_lines_text_file() {
let mut file = NamedTempFile::new().unwrap();
writeln!(file, "line 1").unwrap();
writeln!(file, "line 2").unwrap();
writeln!(file, "line 3").unwrap();
file.flush().unwrap();

let meta = file.path().metadata().unwrap();
let lines = Lines::from_path(file.path(), &meta);
assert_eq!(lines.count, Some(3));
}

#[test]
fn test_lines_binary_file() {
let mut file = NamedTempFile::new().unwrap();
file.write_all(&[0u8, 1u8, 2u8, 0u8]).unwrap();
file.flush().unwrap();

let meta = file.path().metadata().unwrap();
let lines = Lines::from_path(file.path(), &meta);
assert_eq!(lines.count, Some(0)); // Binary files return 0
}

#[test]
fn test_lines_from_total() {
let lines = Lines::from_total(42);
assert_eq!(lines.count, Some(42));
}

#[test]
fn test_value_string_text_file() {
let lines = Lines::from_total(123);
assert_eq!(lines.value_string(), "123");
}

#[test]
fn test_value_string_binary_file() {
let lines = Lines { count: Some(0) };
assert_eq!(lines.value_string(), "-");
}

#[test]
fn test_value_string_none() {
let lines = Lines { count: None };
assert_eq!(lines.value_string(), "-");
}
}
Loading