column.rs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. use std::iter::repeat;
  2. use options::{SizeFormat, TimeType};
  3. use ansi_term::Style;
  4. use unicode_width::UnicodeWidthStr;
  5. #[derive(PartialEq, Debug, Copy, Clone)]
  6. pub enum Column {
  7. Permissions,
  8. FileSize(SizeFormat),
  9. Timestamp(TimeType),
  10. Blocks,
  11. User,
  12. Group,
  13. HardLinks,
  14. Inode,
  15. GitStatus,
  16. }
  17. /// Each column can pick its own **Alignment**. Usually, numbers are
  18. /// right-aligned, and text is left-aligned.
  19. #[derive(Copy, Clone)]
  20. pub enum Alignment {
  21. Left, Right,
  22. }
  23. impl Column {
  24. /// Get the alignment this column should use.
  25. pub fn alignment(&self) -> Alignment {
  26. match *self {
  27. Column::FileSize(_) => Alignment::Right,
  28. Column::HardLinks => Alignment::Right,
  29. Column::Inode => Alignment::Right,
  30. Column::Blocks => Alignment::Right,
  31. Column::GitStatus => Alignment::Right,
  32. _ => Alignment::Left,
  33. }
  34. }
  35. /// Get the text that should be printed at the top, when the user elects
  36. /// to have a header row printed.
  37. pub fn header(&self) -> &'static str {
  38. match *self {
  39. Column::Permissions => "Permissions",
  40. Column::FileSize(_) => "Size",
  41. Column::Timestamp(t) => t.header(),
  42. Column::Blocks => "Blocks",
  43. Column::User => "User",
  44. Column::Group => "Group",
  45. Column::HardLinks => "Links",
  46. Column::Inode => "inode",
  47. Column::GitStatus => "Git",
  48. }
  49. }
  50. }
  51. /// Pad a string with the given number of spaces.
  52. fn spaces(length: usize) -> String {
  53. repeat(" ").take(length).collect()
  54. }
  55. impl Alignment {
  56. /// Pad a string with the given alignment and number of spaces.
  57. ///
  58. /// This doesn't take the width the string *should* be, rather the number
  59. /// of spaces to add: this is because the strings are usually full of
  60. /// invisible control characters, so getting the displayed width of the
  61. /// string is not as simple as just getting its length.
  62. pub fn pad_string(&self, string: &str, padding: usize) -> String {
  63. match *self {
  64. Alignment::Left => format!("{}{}", string, spaces(padding)),
  65. Alignment::Right => format!("{}{}", spaces(padding), string),
  66. }
  67. }
  68. }
  69. #[derive(PartialEq, Debug)]
  70. pub struct Cell {
  71. pub length: usize,
  72. pub text: String,
  73. }
  74. impl Cell {
  75. pub fn paint(style: Style, string: &str) -> Cell {
  76. Cell {
  77. text: style.paint(string).to_string(),
  78. length: UnicodeWidthStr::width(string),
  79. }
  80. }
  81. }