table.rs 13 KB

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