Rust Cli Cross

creating a basic cli using Crossterm lib with Rust

Rust Cli Crossterm

Crossterm is a terminal library for Rust, which provides an easy-to-use interface for writing terminal applications in Rust.

To start the application, you can use the following command:

cargo run

Code

Adding the crossterm dependency to Cargo.toml:

[dependencies]
crossterm = "0.27.0"

Now let’s add a basic Hello World program to our project (a hello world for cli):

use crossterm::{
    execute,
    style::{Color, Print, ResetColor, SetForegroundColor},
    terminal,
    cursor,
};

fn main() {
    // Setup terminal
    execute!(
        std::io::stdout(),
        cursor::Hide
    )
    .expect("Failed to enter alternate screen");

    // Ask for user's name
    print!("Enter your name: ");
    std::io::Write::flush(&mut std::io::stdout()).unwrap();

    let mut name = String::new();
    std::io::stdin()
        .read_line(&mut name)
        .expect("Failed to read line");

    // Greet the user
    execute!(
        std::io::stdout(),
        SetForegroundColor(Color::Yellow),
        Print(format!("Hello, {}!\n", name.trim())),
        ResetColor,
        cursor::Show,
    )
    .expect("Failed to execute commands");

    // Cleanup
    terminal::disable_raw_mode().expect("Failed to disable raw mode");
}

Explaining the code:

  • First, we import the crossterm crate.
  • Next, we create a function called main that will be called when the application is started.
  • Inside the function, we setup the terminal.
  • Then, we ask the user’s name.
  • Then, we greet the user.
  • Finally, we cleanup the terminal.

Conclusion

Crossterm is a terminal library for Rust, which provides an easy-to-use interface for writing terminal applications in Rust.

0%