table.rs 13 KB

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