table.rs 12 KB

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