Sure! Below is a simple Rust CLI tool for managing a todo.txt style todo list. It supports adding, listing, and completing tasks stored in a plain text file (todo.txt).
Features:
- Add a new todo item
- List all todo items with their index
- Mark a todo item as done (removes it from the list)
Code
use std::env;
use std::fs::{self, OpenOptions};
use std::io::{self, BufRead, BufReader, Write};
use std::path::Path;
const TODO_FILE: &str = "todo.txt";
fn main() -> io::Result<()> {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
print_usage();
return Ok(());
}
match args[1].as_str() {
"add" => {
if args.len() < 3 {
eprintln!("Error: Missing todo item to add.");
print_usage();
return Ok(());
}
let item = args[2..].join(" ");
add_todo(&item)?;
}
"list" => {
list_todos()?;
}
"done" => {
if args.len() != 3 {
eprintln!("Error: Specify the index of the todo to mark done.");
print_usage();
return Ok(());
}
let index: usize = match args[2].parse() {
Ok(i) => i,
Err(_) => {
eprintln!("Error: Invalid index '{}'", args[2]);
return Ok(());
}
};
mark_done(index)?;
}
_ => {
eprintln!("Unknown command: {}", args[1]);
print_usage();
}
}
Ok(())
}
fn print_usage() {
println!("Usage:");
println!(" todo add <task> Add a new todo item");
println!(" todo list List all todo items");
println!(" todo done <index> Mark a todo item as done");
}
fn add_todo(item: &str) -> io::Result<()> {
let mut file = OpenOptions::new()
.create(true)
.append(true)
.open(TODO_FILE)?;
writeln!(file, "{}", item)?;
println!("Added todo: {}", item);
Ok(())
}
fn list_todos() -> io::Result<()> {
if !Path::new(TODO_FILE).exists() {
println!("No todos found.");
return Ok(());
}
let file = OpenOptions::new().read(true).open(TODO_FILE)?;
let reader = BufReader::new(file);
for (i, line) in reader.lines().enumerate() {
let line = line?;
println!("{}: {}", i + 1, line);
}
Ok(())
}
fn mark_done(index: usize) -> io::Result<()> {
if !Path::new(TODO_FILE).exists() {
eprintln!("No todos found.");
return Ok(());
}
let file = OpenOptions::new().read(true).open(TODO_FILE)?;
let reader = BufReader::new(file);
let mut todos: Vec<String> = reader.lines().collect::<Result<_, _>>()?;
if index == 0 || index > todos.len() {
eprintln!("Invalid todo index: {}", index);
return Ok(());
}
let removed = todos.remove(index - 1);
fs::write(TODO_FILE, todos.join("\n") + if todos.is_empty() { "" } else { "\n" })?;
println!("Marked done: {}", removed);
Ok(())
}
How to use
- Save the code to
src/main.rs in a new Rust project (cargo new todo).
- Build with
cargo build --release.
- Run the tool:
./target/release/todo add "Buy milk"
./target/release/todo add "Write Rust CLI"
./target/release/todo list
./target/release/todo done 1
./target/release/todo list
If you want me to add more features like due dates, priorities, or integration with todo.txt format conventions, just ask!