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.

89 lines
2.2 KiB

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