Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 38 ยท Projects and Practice

Project: A Command-Line To-Do Manager in Groovy

Build a complete Groovy command-line to-do manager: CliBuilder options, a Task class with @Canonical, JSON file storage with JsonSlurper, and Spock tests.

This project puts the course together in one small but real program: a to-do manager you run from a terminal. It uses a value class with AST annotations, closures for filtering, JsonSlurper and JsonBuilder for persistence, CliBuilder for options, and a Spock specification to test the logic. You will design the program in layers so that the logic is easy to test and the command-line shell stays thin.

Groovy cannot run on this site, so the Groovy source is read-only. The Java program near the end ports the core logic and runs here, so you can check the algorithm and see the output.

What the program does

TEXT
todo add "Buy milk" --due 2025-06-01
todo list
todo list --open
todo done 2
todo remove 3

Tasks are stored in todos.json in the current directory. Each has an id, a title, an optional due date and a done flag.

Layer 1: the model

GROOVY
// Task.groovy
import groovy.transform.Canonical

@Canonical
class Task {
  int id
  String title
  String due          // "2025-06-01" or null
  boolean done = false

  String toString() {
    "${done ? '[x]' : '[ ]'} ${id}. ${title}${due ? ' (due ' + due + ')' : ''}"
  }
}

@Canonical generates the constructor, equals, hashCode and a default toString; we override toString with a friendlier line. The default done = false becomes an optional constructor argument.

Layer 2: the store

The store owns the list and the file. It knows nothing about the command line.

GROOVY
// TodoStore.groovy
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper

class TodoStore {
  private final File file
  private List<Task> tasks = []

  TodoStore(File file) {
    this.file = file
    load()
  }

  private void load() {
    if (!file.exists()) return
    def data = new JsonSlurper().parse(file)
    tasks = data.collect { new Task(it.id, it.title, it.due, it.done) }
  }

  private void save() {
    file.text = new JsonBuilder(tasks.collect {
      [id: it.id, title: it.title, due: it.due, done: it.done]
    }).toPrettyString()
  }

  Task add(String title, String due = null) {
    int nextId = (tasks*.id.max() ?: 0) + 1
    def task = new Task(nextId, title, due)
    tasks << task
    save()
    task
  }

  boolean markDone(int id) {
    def t = tasks.find { it.id == id }
    if (!t) return false
    t.done = true
    save()
    true
  }

  boolean remove(int id) {
    def removed = tasks.removeAll { it.id == id }
    if (removed) save()
    removed
  }

  List<Task> list(boolean openOnly = false) {
    def result = openOnly ? tasks.findAll { !it.done } : tasks
    result.sort(false) { a, b -> a.due <=> b.due ?: a.id <=> b.id }
  }
}

Idioms to notice: tasks*.id.max() ?: 0 (spread, max, Elvis for an empty list), find/findAll/removeAll with closures, and the sort comparator that compares due dates first and breaks ties by id. sort(false) returns a new list and leaves the original alone. The spaceship operator <=> treats null as smaller than anything, so tasks without a due date come first; if you prefer them last, compare a.due ?: "9999".

Layer 3: the command line

GROOVY
// todo.groovy  (run with: groovy todo.groovy add "Buy milk" --due 2025-06-01)
def cli = new CliBuilder(usage: 'todo <command> [options]')
cli.with {
  h longOpt: 'help', 'Show usage'
  d longOpt: 'due', args: 1, argName: 'date', 'Due date (yyyy-mm-dd)'
  o longOpt: 'open', 'Only open tasks'
}
def opts = cli.parse(args)
if (!opts || opts.h || !opts.arguments()) {
  cli.usage()
  return
}

def store = new TodoStore(new File('todos.json'))
def (cmd, rest) = [opts.arguments()[0], opts.arguments().drop(1)]

switch (cmd) {
  case 'add':
    println "Added: " + store.add(rest.join(' '), opts.d ?: null)
    break
  case 'list':
    store.list(opts.o).each { println it }
    break
  case 'done':
    println store.markDone(rest[0] as int) ? "Done." : "No such task."
    break
  case 'remove':
    println store.remove(rest[0] as int) ? "Removed." : "No such task."
    break
  default:
    cli.usage()
}

CliBuilder is a DSL: each line in cli.with { ... } declares an option (h, d, o) with a long name and a description. cli.parse(args) returns an object where opts.d is the value of --due, opts.o is a boolean, and opts.arguments() are the non-option arguments. In recent Groovy versions the class is groovy.cli.commons.CliBuilder, imported automatically in scripts through the default imports of the distribution, or explicitly with import groovy.cli.commons.CliBuilder.

Layer 4: a Spock specification

GROOVY
import spock.lang.*
import java.nio.file.Files

class TodoStoreSpec extends Specification {

  @TempDir File dir
  TodoStore store

  def setup() {
    store = new TodoStore(new File(dir, "todos.json"))
  }

  def "ids increase from 1"() {
    when:
    def a = store.add("a")
    def b = store.add("b")

    then:
    a.id == 1
    b.id == 2
  }

  def "done tasks are hidden from the open list"() {
    given:
    store.add("a")
    store.add("b")

    when:
    store.markDone(1)

    then:
    store.list(true)*.title == ["b"]
  }

  def "unknown ids are reported"() {
    expect:
    !store.markDone(99)
    !store.remove(99)
  }

  def "tasks survive a restart"() {
    given:
    store.add("keep me", "2025-06-01")

    when:
    def reopened = new TodoStore(new File(dir, "todos.json"))

    then:
    reopened.list()*.title == ["keep me"]
  }
}

@TempDir gives each feature a fresh temporary directory, so tests never touch your real file and never interfere with each other. The restart test proves the JSON round trip.

Extending the project

  1. Validate the date format and reject bad input with a clear message.
  2. Add edit <id> <new title> and priorities (--high).
  3. Replace the switch with a map of command names to closures: commands = [add: { ... }, list: { ... }].
  4. Turn the project into a Gradle build with application and Spock (see Gradle build scripts).
  5. Add --json output using JsonOutput.prettyPrint(JsonOutput.toJson(...)).

Try it: the core logic ported to Java (stand-in)

The Java version below runs the store logic in memory (no file) and prints the same lines the Groovy program would print.

Java Stand-in: to-do store logic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Try it: command dispatch with a map (stand-in)

Extension idea 3: a map from command name to action replaces the switch.

Java Stand-in: commands as a map of functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the store separated from the command-line script?

    A thin shell over a testable core is easier to verify and to reuse with another interface.
  2. 2. What does tasks*.id.max() ?: 0 produce for an empty list?

    The spread collects ids, max() of an empty list is null, and ?: replaces null with 0.
  3. 3. What is @TempDir used for in the Spock specification?

    Each feature gets its own temp directory that is cleaned up afterwards.
  4. 4. What does sort(false) { ... } do?

    Passing false as the mutate flag returns a new list, protecting the stored order.

Summary

  • The project has four layers: model (@Canonical), store (JSON, closures), command line (CliBuilder) and tests (Spock).
  • Keep logic out of the shell so it can be tested.
  • Persistence with JsonSlurper and JsonBuilder is a few lines.
  • Spock's @TempDir makes file-based tests safe.

Next: Project: A Log File Analyzer