Guides · 02

Build a Terminal Task Manager

Build an interactive terminal task manager with structs, impl methods, Copy-on-Write nested state updates, and JSON persistence.

In this guide you will build a terminal task manager that models tasks with a struct, updates nested task fields safely using var + Copy-on-Write, and persists tasks to disk as JSON.

Step 1: Model the Task Struct

struct Task {
    id: Int,
    title: Str,
    done: Bool,
}

impl Task {
    fn format(self) -> Str {
        let box = if self.done { "[x]" } else { "[ ]" }
        return "{self.id}. {box} {self.title}"
    }
}

fn main() {
    var tasks = [
        Task { id: 1, title: "Design schema", done: true },
        Task { id: 2, title: "Write tests", done: false },
    ]

    // Mutate nested struct field inside a var List (Copy-on-Write)
    tasks[1].done = true

    for t in tasks {
        println(t.format())
    }
}

Expected Output

1. [x] Design schema
2. [x] Write tests

Step 2: Interactive Terminal Loop with File Persistence (tasks.och)

Run this complete CLI application with ochre tasks.och:

struct Task {
    id: Int,
    title: Str,
    done: Bool,
}

impl Task {
    fn format(self) -> Str {
        let box = if self.done { "[x]" } else { "[ ]" }
        return "{self.id}. {box} {self.title}"
    }
}

fn save_summary(path: Str, tasks: List<Task>) -> Void!Str {
    let labels = map(tasks, (t) => t.format())
    let payload = json_stringify(labels)
    write_file(path, payload)?
    return Ok(void_noop())
}

fn void_noop() {}

fn main() {
    var tasks: List<Task> = []
    var next_id = 1
    var running = true

    println("Ochre Task Manager — commands: add, list, done, save, quit")
    while running {
        let cmd = trim(input("> "))
        if cmd == "add" {
            let title = trim(input("Title: "))
            if len(title) > 0 {
                tasks = push(tasks, Task { id: next_id, title: title, done: false })
                next_id += 1
                println("Added task.")
            }
        } else if cmd == "list" {
            if len(tasks) == 0 {
                println("(no tasks yet)")
            } else {
                for t in tasks {
                    println(t.format())
                }
            }
        } else if cmd == "done" {
            let idx = int(trim(input("Task ID: "))) - 1
            if idx >= 0 && idx < len(tasks) {
                tasks[idx].done = true
                println("Marked complete.")
            } else {
                println("Invalid task ID.")
            }
        } else if cmd == "save" {
            match save_summary("tasks.json", tasks) {
                Ok(_) => println("Saved to tasks.json"),
                Err(e) => println("Save failed: {e}"),
            }
        } else if cmd == "quit" {
            running = false
        } else {
            println("Unknown command: {cmd}")
        }
    }
}