table.rs 15 KB

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