You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.0 KiB

  1. use colored::Colorize;
  2. use std::env;
  3. use whoami::{hostname, username};
  4. #[derive(Clone)]
  5. pub enum PromptStyle {
  6. Default,
  7. SimpleDirectory,
  8. BashLike,
  9. }
  10. impl PromptStyle {
  11. pub fn fmt_style(&self) -> String {
  12. match self {
  13. PromptStyle::Default => self.fmt_default(),
  14. PromptStyle::SimpleDirectory => self.fmt_simple_directory(),
  15. PromptStyle::BashLike => self.fmt_bash_like(),
  16. }
  17. }
  18. fn fmt_default(&self) -> String {
  19. let current = env::current_dir().unwrap_or_default();
  20. let home = dirs::home_dir().unwrap_or_default();
  21. let dir = if current.starts_with(home.clone()) {
  22. let mut path = "~/".to_string();
  23. path.push_str(
  24. current
  25. .as_path()
  26. .strip_prefix(home)
  27. .unwrap()
  28. .to_str()
  29. .unwrap_or_default(),
  30. );
  31. path
  32. } else {
  33. current.into_os_string().into_string().unwrap_or_default()
  34. };
  35. format!(
  36. "\n{}\n{} ",
  37. dir.bright_cyan().bold(),
  38. "»".bright_green().bold()
  39. )
  40. }
  41. fn fmt_simple_directory(&self) -> String {
  42. let path = env::current_dir().unwrap_or_default();
  43. format!("{} » ", path.to_string_lossy())
  44. }
  45. fn fmt_bash_like(&self) -> String {
  46. let path = env::current_dir().unwrap_or_default();
  47. let home = dirs::home_dir().unwrap_or_default();
  48. let dir_as_string = if path == home {
  49. "~"
  50. } else {
  51. path.file_name()
  52. .unwrap_or_default()
  53. .to_str()
  54. .unwrap_or_default()
  55. };
  56. format!("[{}@{} {}]$ ", username(), hostname(), dir_as_string)
  57. }
  58. }
  59. pub struct Prompt {
  60. pub style: PromptStyle,
  61. }
  62. impl Prompt {
  63. pub fn new() -> Self {
  64. Self {
  65. style: PromptStyle::Default,
  66. }
  67. }
  68. pub fn get_prompt(&mut self) -> String {
  69. self.style.fmt_style()
  70. }
  71. }