Skip to main content

lx_cli/formatter/
long.rs

1use crate::config::{Config, LongField};
2use crate::file_entry::FileEntry;
3use crate::formatter::render::{Renderer, push_spaces};
4use crate::formatter::{filename_width, print_line};
5use crate::sort::{SortOptions, sort_entries};
6use chrono::format::Item;
7use chrono::{DateTime, FixedOffset};
8use std::collections::HashMap;
9use std::fmt::Write as _;
10use std::io::{self, Write};
11use std::mem::MaybeUninit;
12use std::time::SystemTime;
13use unicode_width::UnicodeWidthStr;
14
15pub fn format_long(
16    out: &mut dyn Write,
17    mut entries: Vec<FileEntry>,
18    config: &Config,
19    sort: SortOptions,
20) -> io::Result<()> {
21    sort_entries(&mut entries, sort);
22    if entries.is_empty() {
23        return Ok(());
24    }
25    print_long_entries(out, &entries, None, config)
26}
27
28/// Prints titles and rows; tree branches, when given, are drawn inside the Name column.
29pub fn print_long_entries(
30    out: &mut dyn Write,
31    entries: &[FileEntry],
32    filename_prefixes: Option<&[String]>,
33    config: &Config,
34) -> io::Result<()> {
35    let layout = LongLayout::new(entries, filename_prefixes, config);
36    if config.display.long_format_titles {
37        print_long_titles(out, config, &layout)?;
38    }
39    print_long_rows(out, entries, config, &layout, filename_prefixes)
40}
41
42/// Columns, their widths, and each entry's formatted date, computed once per listing.
43struct LongLayout<'config> {
44    fields: &'config [LongField],
45    widths: HashMap<LongField, usize>,
46    modified: Vec<String>,
47}
48
49impl<'config> LongLayout<'config> {
50    fn new(
51        entries: &[FileEntry],
52        filename_prefixes: Option<&[String]>,
53        config: &'config Config,
54    ) -> Self {
55        let fields = config.display.long_format_fields.as_slice();
56        let modified = if fields.contains(&LongField::Modified) {
57            format_modified_entries(entries, &config.display.datetime_items())
58        } else {
59            vec![String::new(); entries.len()]
60        };
61        let mut widths = HashMap::new();
62        for &field in fields {
63            let width = match field {
64                LongField::Git => entries
65                    .iter()
66                    .filter_map(|entry| entry.git_status)
67                    .map(|status| UnicodeWidthStr::width(status.badge(config.icons.enabled)))
68                    .max()
69                    .unwrap_or(0),
70                LongField::Nlink => entries
71                    .iter()
72                    .map(|e| e.nlink.to_string().len())
73                    .max()
74                    .unwrap_or(0),
75                LongField::Owner => entries
76                    .iter()
77                    .map(|entry| UnicodeWidthStr::width(entry.owner.as_str()))
78                    .max()
79                    .unwrap_or(0),
80                LongField::Group => entries
81                    .iter()
82                    .map(|entry| UnicodeWidthStr::width(entry.group.as_str()))
83                    .max()
84                    .unwrap_or(0),
85                LongField::Size => entries
86                    .iter()
87                    .map(|e| e.format_size().to_string().len())
88                    .max()
89                    .unwrap_or(0),
90                LongField::Modified => modified
91                    .iter()
92                    .map(|value| UnicodeWidthStr::width(value.as_str()))
93                    .max()
94                    .unwrap_or(0),
95                LongField::Filename => entries
96                    .iter()
97                    .enumerate()
98                    .map(|(index, entry)| {
99                        filename_width(entry, config)
100                            + filename_prefixes
101                                .and_then(|prefixes| prefixes.get(index))
102                                .map_or(0, |prefix| UnicodeWidthStr::width(prefix.as_str()))
103                    })
104                    .max()
105                    .unwrap_or(0),
106                LongField::Permissions => entries
107                    .iter()
108                    .map(|e| e.format_permissions().len())
109                    .max()
110                    .unwrap_or(0),
111            };
112            let title_width = if config.display.long_format_titles {
113                UnicodeWidthStr::width(field.title())
114            } else {
115                0
116            };
117            widths.insert(field, width.max(title_width));
118        }
119        Self {
120            fields,
121            widths,
122            modified,
123        }
124    }
125
126    fn width(&self, field: LongField) -> usize {
127        self.widths.get(&field).copied().unwrap_or(0)
128    }
129}
130
131fn print_long_rows(
132    out: &mut dyn Write,
133    entries: &[FileEntry],
134    config: &Config,
135    layout: &LongLayout<'_>,
136    filename_prefixes: Option<&[String]>,
137) -> io::Result<()> {
138    let fields = layout.fields;
139    let renderer = Renderer::new(config);
140    let tree_style = config.theme.style("tree");
141    let separator = " ".repeat(config.display.column_spacing);
142    // One buffer reused for every row.
143    let mut line = String::new();
144    for (entry_index, entry) in entries.iter().enumerate() {
145        line.clear();
146        let mut first = true;
147        for (index, &field) in fields.iter().enumerate() {
148            let mut cell = renderer.field(entry, field, &layout.modified[entry_index]);
149            let filename_prefix = match field {
150                LongField::Filename => filename_prefixes
151                    .and_then(|prefixes| prefixes.get(entry_index))
152                    .map_or("", String::as_str),
153                _ => "",
154            };
155            if cell.text.is_empty() && filename_prefix.is_empty() {
156                continue;
157            }
158            if !first {
159                line.push_str(&separator);
160            }
161            first = false;
162            if !filename_prefix.is_empty() {
163                let mut text = String::with_capacity(filename_prefix.len() + cell.text.len() + 16);
164                tree_style.paint_into(&mut text, filename_prefix);
165                text.push_str(&cell.text);
166                cell.text = text;
167                cell.width += UnicodeWidthStr::width(filename_prefix);
168            }
169            let right = matches!(field, LongField::Size | LongField::Nlink);
170            let width = if right || index < fields.len() - 1 {
171                layout.width(field)
172            } else {
173                cell.width
174            };
175            cell.write_padded(&mut line, width, right);
176        }
177        line.push('\n');
178        out.write_all(line.as_bytes())?;
179    }
180    Ok(())
181}
182
183/// Converts to local time with the C library, which honours `TZ` like `ls`.
184///
185/// chrono's own `Local` needs its `clock` feature, which links CoreFoundation on macOS and
186/// adds about a millisecond to every launch.
187fn local_datetime(time: SystemTime) -> DateTime<FixedOffset> {
188    let (seconds, nanoseconds) = match time.duration_since(SystemTime::UNIX_EPOCH) {
189        Ok(duration) => (duration.as_secs() as i64, duration.subsec_nanos()),
190        Err(error) => {
191            let before = error.duration();
192            match before.subsec_nanos() {
193                0 => (-(before.as_secs() as i64), 0),
194                nanoseconds => (-(before.as_secs() as i64) - 1, 1_000_000_000 - nanoseconds),
195            }
196        }
197    };
198    let utc = DateTime::from_timestamp(seconds, nanoseconds).unwrap_or_default();
199    let mut local = MaybeUninit::<libc::tm>::uninit();
200    let time = seconds as libc::time_t;
201    // SAFETY: both pointers are valid; `localtime_r` initialises `local` when it succeeds.
202    let offset = if unsafe { libc::localtime_r(&time, local.as_mut_ptr()) }.is_null() {
203        0
204    } else {
205        // SAFETY: checked above that `localtime_r` succeeded.
206        unsafe { local.assume_init() }.tm_gmtoff as i32
207    };
208    utc.with_timezone(&FixedOffset::east_opt(offset).unwrap_or(FixedOffset::east_opt(0).unwrap()))
209}
210
211/// Formats every entry's date, padding each numeric or text component to a shared width.
212fn format_modified_entries(entries: &[FileEntry], datetime_items: &[Item<'_>]) -> Vec<String> {
213    #[derive(Clone, Copy, PartialEq)]
214    enum Alignment {
215        Left,
216        Right,
217        None,
218    }
219    let alignments: Vec<Alignment> = datetime_items
220        .iter()
221        .map(|item| match item {
222            Item::Numeric(_, _) => Alignment::Right,
223            Item::Fixed(_) => Alignment::Left,
224            _ => Alignment::None,
225        })
226        .collect();
227
228    // All components go into one buffer; `ends` marks where each finishes.
229    let mut text = String::new();
230    let mut ends = Vec::with_capacity(entries.len() * datetime_items.len());
231    for entry in entries {
232        let datetime = local_datetime(entry.modified);
233        for item in datetime_items {
234            let _ = write!(
235                text,
236                "{}",
237                datetime.format_with_items(std::iter::once(item))
238            );
239            ends.push(text.len());
240        }
241    }
242    let component = |index: usize| {
243        let start = index.checked_sub(1).map_or(0, |previous| ends[previous]);
244        &text[start..ends[index]]
245    };
246
247    let mut widths = vec![0; datetime_items.len()];
248    for index in 0..ends.len() {
249        let column = index % datetime_items.len();
250        if alignments[column] != Alignment::None {
251            widths[column] = widths[column].max(UnicodeWidthStr::width(component(index)));
252        }
253    }
254
255    (0..entries.len())
256        .map(|entry_index| {
257            let mut formatted = String::new();
258            for column in 0..datetime_items.len() {
259                let value = component(entry_index * datetime_items.len() + column);
260                let padding = widths[column].saturating_sub(UnicodeWidthStr::width(value));
261                match alignments[column] {
262                    Alignment::Left => {
263                        formatted.push_str(value);
264                        push_spaces(&mut formatted, padding);
265                    }
266                    Alignment::Right => {
267                        push_spaces(&mut formatted, padding);
268                        formatted.push_str(value);
269                    }
270                    Alignment::None => formatted.push_str(value),
271                }
272            }
273            formatted
274        })
275        .collect()
276}
277
278fn print_long_titles(
279    out: &mut dyn Write,
280    config: &Config,
281    layout: &LongLayout<'_>,
282) -> io::Result<()> {
283    let fields = layout.fields;
284    let titles: Vec<String> = fields
285        .iter()
286        .enumerate()
287        .map(|(index, &field)| {
288            let title = field.title();
289            let padding = if index < fields.len() - 1 {
290                layout
291                    .width(field)
292                    .saturating_sub(UnicodeWidthStr::width(title))
293            } else {
294                0
295            };
296
297            format!(
298                "{}{}",
299                config.theme.style("header").paint(title),
300                " ".repeat(padding)
301            )
302        })
303        .collect();
304
305    print_line(
306        out,
307        format_args!(
308            "{}",
309            titles.join(&" ".repeat(config.display.column_spacing))
310        ),
311    )
312}