table.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. use std::cmp::max;
  2. use std::env;
  3. use std::ops::Deref;
  4. #[cfg(unix)]
  5. use std::sync::{Mutex, MutexGuard};
  6. use datetime::TimeZone;
  7. use zoneinfo_compiled::{CompiledData, Result as TZResult};
  8. use lazy_static::lazy_static;
  9. use log::*;
  10. #[cfg(unix)]
  11. use users::UsersCache;
  12. use crate::fs::{File, fields as f};
  13. use crate::fs::feature::git::GitCache;
  14. use crate::output::cell::TextCell;
  15. use crate::output::render::TimeRender;
  16. use crate::output::time::TimeFormat;
  17. use crate::theme::Theme;
  18. /// Options for displaying a table.
  19. #[derive(PartialEq, Eq, Debug)]
  20. pub struct Options {
  21. pub size_format: SizeFormat,
  22. pub time_format: TimeFormat,
  23. pub user_format: UserFormat,
  24. pub columns: Columns,
  25. }
  26. /// Extra columns to display in the table.
  27. #[allow(clippy::struct_excessive_bools)]
  28. #[derive(PartialEq, Eq, Debug, Copy, Clone)]
  29. pub struct Columns {
  30. /// At least one of these timestamps will be shown.
  31. pub time_types: TimeTypes,
  32. // The rest are just on/off
  33. pub inode: bool,
  34. pub links: bool,
  35. pub blocks: bool,
  36. pub group: bool,
  37. pub git: bool,
  38. pub subdir_git_repos: bool,
  39. pub subdir_git_repos_no_stat: bool,
  40. pub octal: bool,
  41. pub security_context: bool,
  42. // Defaults to true:
  43. pub permissions: bool,
  44. pub filesize: bool,
  45. pub user: bool,
  46. }
  47. impl Columns {
  48. pub fn collect(&self, actually_enable_git: bool) -> Vec<Column> {
  49. let mut columns = Vec::with_capacity(4);
  50. if self.inode {
  51. #[cfg(unix)]
  52. columns.push(Column::Inode);
  53. }
  54. if self.octal {
  55. #[cfg(unix)]
  56. columns.push(Column::Octal);
  57. }
  58. if self.permissions {
  59. columns.push(Column::Permissions);
  60. }
  61. if self.links {
  62. #[cfg(unix)]
  63. columns.push(Column::HardLinks);
  64. }
  65. if self.filesize {
  66. columns.push(Column::FileSize);
  67. }
  68. if self.blocks {
  69. #[cfg(unix)]
  70. columns.push(Column::Blocks);
  71. }
  72. if self.user {
  73. #[cfg(unix)]
  74. columns.push(Column::User);
  75. }
  76. if self.group {
  77. #[cfg(unix)]
  78. columns.push(Column::Group);
  79. }
  80. if self.security_context {
  81. columns.push(Column::SecurityContext);
  82. }
  83. if self.time_types.modified {
  84. columns.push(Column::Timestamp(TimeType::Modified));
  85. }
  86. if self.time_types.changed {
  87. columns.push(Column::Timestamp(TimeType::Changed));
  88. }
  89. if self.time_types.created {
  90. columns.push(Column::Timestamp(TimeType::Created));
  91. }
  92. if self.time_types.accessed {
  93. columns.push(Column::Timestamp(TimeType::Accessed));
  94. }
  95. if self.git && actually_enable_git {
  96. columns.push(Column::GitStatus);
  97. }
  98. if self.subdir_git_repos {
  99. columns.push(Column::SubdirGitRepoStatus);
  100. }
  101. if self.subdir_git_repos_no_stat {
  102. columns.push(Column::SubdirGitRepoNoStatus);
  103. }
  104. columns
  105. }
  106. }
  107. /// A table contains these.
  108. #[derive(Debug, Copy, Clone)]
  109. pub enum Column {
  110. Permissions,
  111. FileSize,
  112. Timestamp(TimeType),
  113. #[cfg(unix)]
  114. Blocks,
  115. #[cfg(unix)]
  116. User,
  117. #[cfg(unix)]
  118. Group,
  119. #[cfg(unix)]
  120. HardLinks,
  121. #[cfg(unix)]
  122. Inode,
  123. GitStatus,
  124. SubdirGitRepoStatus,
  125. SubdirGitRepoNoStatus,
  126. #[cfg(unix)]
  127. Octal,
  128. #[cfg(unix)]
  129. SecurityContext,
  130. }
  131. /// Each column can pick its own **Alignment**. Usually, numbers are
  132. /// right-aligned, and text is left-aligned.
  133. #[derive(Copy, Clone)]
  134. pub enum Alignment {
  135. Left,
  136. Right,
  137. }
  138. impl Column {
  139. /// Get the alignment this column should use.
  140. #[cfg(unix)]
  141. pub fn alignment(self) -> Alignment {
  142. match self {
  143. Self::FileSize |
  144. Self::HardLinks |
  145. Self::Inode |
  146. Self::Blocks |
  147. Self::GitStatus => Alignment::Right,
  148. Self::Timestamp(_) |
  149. _ => Alignment::Left,
  150. }
  151. }
  152. #[cfg(windows)]
  153. pub fn alignment(&self) -> Alignment {
  154. match self {
  155. Self::FileSize |
  156. Self::GitStatus => Alignment::Right,
  157. _ => Alignment::Left,
  158. }
  159. }
  160. /// Get the text that should be printed at the top, when the user elects
  161. /// to have a header row printed.
  162. pub fn header(self) -> &'static str {
  163. match self {
  164. #[cfg(unix)]
  165. Self::Permissions => "Permissions",
  166. #[cfg(windows)]
  167. Self::Permissions => "Mode",
  168. Self::FileSize => "Size",
  169. Self::Timestamp(t) => t.header(),
  170. #[cfg(unix)]
  171. Self::Blocks => "Blocks",
  172. #[cfg(unix)]
  173. Self::User => "User",
  174. #[cfg(unix)]
  175. Self::Group => "Group",
  176. #[cfg(unix)]
  177. Self::HardLinks => "Links",
  178. #[cfg(unix)]
  179. Self::Inode => "inode",
  180. Self::GitStatus => "Git",
  181. Self::SubdirGitRepoStatus => "Repo",
  182. Self::SubdirGitRepoNoStatus => "Repo",
  183. #[cfg(unix)]
  184. Self::Octal => "Octal",
  185. #[cfg(unix)]
  186. Self::SecurityContext => "Security Context",
  187. }
  188. }
  189. }
  190. /// Formatting options for file sizes.
  191. #[allow(clippy::enum_variant_names)]
  192. #[derive(PartialEq, Eq, Debug, Copy, Clone)]
  193. pub enum SizeFormat {
  194. /// Format the file size using **decimal** prefixes, such as “kilo”,
  195. /// “mega”, or “giga”.
  196. DecimalBytes,
  197. /// Format the file size using **binary** prefixes, such as “kibi”,
  198. /// “mebi”, or “gibi”.
  199. BinaryBytes,
  200. /// Do no formatting and just display the size as a number of bytes.
  201. JustBytes,
  202. }
  203. /// Formatting options for user and group.
  204. #[derive(PartialEq, Eq, Debug, Copy, Clone)]
  205. pub enum UserFormat {
  206. /// The UID / GID
  207. Numeric,
  208. /// Show the name
  209. Name,
  210. }
  211. impl Default for SizeFormat {
  212. fn default() -> Self {
  213. Self::DecimalBytes
  214. }
  215. }
  216. /// The types of a file’s time fields. These three fields are standard
  217. /// across most (all?) operating systems.
  218. #[derive(PartialEq, Eq, Debug, Copy, Clone)]
  219. pub enum TimeType {
  220. /// The file’s modified time (`st_mtime`).
  221. Modified,
  222. /// The file’s changed time (`st_ctime`)
  223. Changed,
  224. /// The file’s accessed time (`st_atime`).
  225. Accessed,
  226. /// The file’s creation time (`btime` or `birthtime`).
  227. Created,
  228. }
  229. impl TimeType {
  230. /// Returns the text to use for a column’s heading in the columns output.
  231. pub fn header(self) -> &'static str {
  232. match self {
  233. Self::Modified => "Date Modified",
  234. Self::Changed => "Date Changed",
  235. Self::Accessed => "Date Accessed",
  236. Self::Created => "Date Created",
  237. }
  238. }
  239. }
  240. /// Fields for which of a file’s time fields should be displayed in the
  241. /// columns output.
  242. ///
  243. /// There should always be at least one of these — there’s no way to disable
  244. /// the time columns entirely (yet).
  245. #[derive(PartialEq, Eq, Debug, Copy, Clone)]
  246. #[allow(clippy::struct_excessive_bools)]
  247. pub struct TimeTypes {
  248. pub modified: bool,
  249. pub changed: bool,
  250. pub accessed: bool,
  251. pub created: bool,
  252. }
  253. impl Default for TimeTypes {
  254. /// By default, display just the ‘modified’ time. This is the most
  255. /// common option, which is why it has this shorthand.
  256. fn default() -> Self {
  257. Self {
  258. modified: true,
  259. changed: false,
  260. accessed: false,
  261. created: false,
  262. }
  263. }
  264. }
  265. /// The **environment** struct contains any data that could change between
  266. /// running instances of exa, depending on the user’s computer’s configuration.
  267. ///
  268. /// Any environment field should be able to be mocked up for test runs.
  269. pub struct Environment {
  270. /// Localisation rules for formatting numbers.
  271. numeric: locale::Numeric,
  272. /// The computer’s current time zone. This gets used to determine how to
  273. /// offset files’ timestamps.
  274. tz: Option<TimeZone>,
  275. /// Mapping cache of user IDs to usernames.
  276. #[cfg(unix)]
  277. users: Mutex<UsersCache>,
  278. }
  279. impl Environment {
  280. #[cfg(unix)]
  281. pub fn lock_users(&self) -> MutexGuard<'_, UsersCache> {
  282. self.users.lock().unwrap()
  283. }
  284. fn load_all() -> Self {
  285. let tz = match determine_time_zone() {
  286. Ok(t) => {
  287. Some(t)
  288. }
  289. Err(ref e) => {
  290. eprintln!("Unable to determine time zone: {e}");
  291. None
  292. }
  293. };
  294. let numeric = locale::Numeric::load_user_locale()
  295. .unwrap_or_else(|_| locale::Numeric::english());
  296. #[cfg(unix)]
  297. let users = Mutex::new(UsersCache::new());
  298. Self { numeric, tz, #[cfg(unix)] users }
  299. }
  300. }
  301. #[cfg(unix)]
  302. fn determine_time_zone() -> TZResult<TimeZone> {
  303. if let Ok(file) = env::var("TZ") {
  304. TimeZone::from_file({
  305. if file.starts_with('/') {
  306. file
  307. } else {
  308. format!("/usr/share/zoneinfo/{}", {
  309. if file.starts_with(':') {
  310. file.replacen(':', "", 1)
  311. } else {
  312. file
  313. }
  314. })
  315. }
  316. })
  317. } else {
  318. TimeZone::from_file("/etc/localtime")
  319. }
  320. }
  321. #[cfg(windows)]
  322. fn determine_time_zone() -> TZResult<TimeZone> {
  323. use datetime::zone::{FixedTimespan, FixedTimespanSet, StaticTimeZone, TimeZoneSource};
  324. use std::borrow::Cow;
  325. Ok(TimeZone(TimeZoneSource::Static(&StaticTimeZone {
  326. name: "Unsupported",
  327. fixed_timespans: FixedTimespanSet {
  328. first: FixedTimespan {
  329. offset: 0,
  330. is_dst: false,
  331. name: Cow::Borrowed("ZONE_A"),
  332. },
  333. rest: &[(
  334. 1206838800,
  335. FixedTimespan {
  336. offset: 3600,
  337. is_dst: false,
  338. name: Cow::Borrowed("ZONE_B"),
  339. },
  340. )],
  341. },
  342. })))
  343. }
  344. lazy_static! {
  345. static ref ENVIRONMENT: Environment = Environment::load_all();
  346. }
  347. pub struct Table<'a> {
  348. columns: Vec<Column>,
  349. theme: &'a Theme,
  350. env: &'a Environment,
  351. widths: TableWidths,
  352. time_format: TimeFormat,
  353. size_format: SizeFormat,
  354. user_format: UserFormat,
  355. git: Option<&'a GitCache>,
  356. }
  357. #[derive(Clone)]
  358. pub struct Row {
  359. cells: Vec<TextCell>,
  360. }
  361. impl<'a, 'f> Table<'a> {
  362. pub fn new(options: &'a Options, git: Option<&'a GitCache>, theme: &'a Theme) -> Table<'a> {
  363. let columns = options.columns.collect(git.is_some());
  364. let widths = TableWidths::zero(columns.len());
  365. let env = &*ENVIRONMENT;
  366. Table {
  367. theme,
  368. widths,
  369. columns,
  370. git,
  371. env,
  372. time_format: options.time_format,
  373. size_format: options.size_format,
  374. user_format: options.user_format,
  375. }
  376. }
  377. pub fn widths(&self) -> &TableWidths {
  378. &self.widths
  379. }
  380. pub fn header_row(&self) -> Row {
  381. let cells = self.columns.iter()
  382. .map(|c| TextCell::paint_str(self.theme.ui.header, c.header()))
  383. .collect();
  384. Row { cells }
  385. }
  386. pub fn row_for_file(&self, file: &File<'_>, xattrs: bool) -> Row {
  387. let cells = self.columns.iter()
  388. .map(|c| self.display(file, *c, xattrs))
  389. .collect();
  390. Row { cells }
  391. }
  392. pub fn add_widths(&mut self, row: &Row) {
  393. self.widths.add_widths(row)
  394. }
  395. fn permissions_plus(&self, file: &File<'_>, xattrs: bool) -> f::PermissionsPlus {
  396. f::PermissionsPlus {
  397. file_type: file.type_char(),
  398. #[cfg(unix)]
  399. permissions: file.permissions(),
  400. #[cfg(windows)]
  401. attributes: file.attributes(),
  402. xattrs,
  403. }
  404. }
  405. #[cfg(unix)]
  406. fn octal_permissions(&self, file: &File<'_>) -> f::OctalPermissions {
  407. f::OctalPermissions {
  408. permissions: file.permissions(),
  409. }
  410. }
  411. fn display(&self, file: &File<'_>, column: Column, xattrs: bool) -> TextCell {
  412. match column {
  413. Column::Permissions => {
  414. self.permissions_plus(file, xattrs).render(self.theme)
  415. }
  416. Column::FileSize => {
  417. file.size().render(self.theme, self.size_format, &self.env.numeric)
  418. }
  419. #[cfg(unix)]
  420. Column::HardLinks => {
  421. file.links().render(self.theme, &self.env.numeric)
  422. }
  423. #[cfg(unix)]
  424. Column::Inode => {
  425. file.inode().render(self.theme.ui.inode)
  426. }
  427. #[cfg(unix)]
  428. Column::Blocks => {
  429. file.blocks().render(self.theme)
  430. }
  431. #[cfg(unix)]
  432. Column::User => {
  433. file.user().render(self.theme, &*self.env.lock_users(), self.user_format)
  434. }
  435. #[cfg(unix)]
  436. Column::Group => {
  437. file.group().render(self.theme, &*self.env.lock_users(), self.user_format)
  438. }
  439. #[cfg(unix)]
  440. Column::SecurityContext => {
  441. file.security_context().render(self.theme)
  442. }
  443. Column::GitStatus => {
  444. self.git_status(file).render(self.theme)
  445. }
  446. Column::SubdirGitRepoStatus => {
  447. self.subdir_git_repo(file, true).render()
  448. }
  449. Column::SubdirGitRepoNoStatus => {
  450. self.subdir_git_repo(file, false).render()
  451. }
  452. #[cfg(unix)]
  453. Column::Octal => {
  454. self.octal_permissions(file).render(self.theme.ui.octal)
  455. }
  456. Column::Timestamp(TimeType::Modified) => {
  457. file.modified_time().render(self.theme.ui.date, &self.env.tz, self.time_format)
  458. }
  459. Column::Timestamp(TimeType::Changed) => {
  460. file.changed_time().render(self.theme.ui.date, &self.env.tz, self.time_format)
  461. }
  462. Column::Timestamp(TimeType::Created) => {
  463. file.created_time().render(self.theme.ui.date, &self.env.tz, self.time_format)
  464. }
  465. Column::Timestamp(TimeType::Accessed) => {
  466. file.accessed_time().render(self.theme.ui.date, &self.env.tz, self.time_format)
  467. }
  468. }
  469. }
  470. fn git_status(&self, file: &File<'_>) -> f::Git {
  471. debug!("Getting Git status for file {:?}", file.path);
  472. self.git
  473. .map(|g| g.get(&file.path, file.is_directory()))
  474. .unwrap_or_default()
  475. }
  476. fn subdir_git_repo(&self, file: &File<'_>, status : bool) -> f::SubdirGitRepo {
  477. debug!("Getting subdir repo status for path {:?}", file.path);
  478. if file.is_directory(){
  479. return f::SubdirGitRepo::from_path(&file.path, status);
  480. }
  481. f::SubdirGitRepo::default()
  482. }
  483. pub fn render(&self, row: Row) -> TextCell {
  484. let mut cell = TextCell::default();
  485. let iter = row.cells.into_iter()
  486. .zip(self.widths.iter())
  487. .enumerate();
  488. for (n, (this_cell, width)) in iter {
  489. let padding = width - *this_cell.width;
  490. match self.columns[n].alignment() {
  491. Alignment::Left => {
  492. cell.append(this_cell);
  493. cell.add_spaces(padding);
  494. }
  495. Alignment::Right => {
  496. cell.add_spaces(padding);
  497. cell.append(this_cell);
  498. }
  499. }
  500. cell.add_spaces(1);
  501. }
  502. cell
  503. }
  504. }
  505. pub struct TableWidths(Vec<usize>);
  506. impl Deref for TableWidths {
  507. type Target = [usize];
  508. fn deref(&self) -> &Self::Target {
  509. &self.0
  510. }
  511. }
  512. impl TableWidths {
  513. pub fn zero(count: usize) -> Self {
  514. Self(vec![0; count])
  515. }
  516. pub fn add_widths(&mut self, row: &Row) {
  517. for (old_width, cell) in self.0.iter_mut().zip(row.cells.iter()) {
  518. *old_width = max(*old_width, *cell.width);
  519. }
  520. }
  521. pub fn total(&self) -> usize {
  522. self.0.len() + self.0.iter().sum::<usize>()
  523. }
  524. }