Capstone 2: the command line
The task store of the last two lessons becomes a program a person can use: a command line with four verbs, a file that keeps the tasks between runs, and exit statuses a shell can test. It is the shape of every command line tool in the course, from the arguments of lesson 031 to the status codes of lesson 099.
The commands
Four verbs and their arguments: list takes none, add takes a title and a priority, done and drop take an id. The program reads the file at the start of every run and writes it after a change, so two runs see the same tasks.
The model and the storage of lessons 131 and 132 are unchanged; what the program adds is the dispatch, the usage line and the statuses. The whole class is below, and the rest of the page runs it.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Tasks {
enum Status {
OPEN, DONE, DROPPED
}
record Task(int id, String title, Status status, int priority) {
Task {
if (title.isBlank()) {
throw new IllegalArgumentException("empty title");
}
if (title.contains("|")) {
throw new IllegalArgumentException("title with a pipe: " + title);
}
if (priority < 1 || priority > 5) {
throw new IllegalArgumentException("priority " + priority + " outside 1..5");
}
}
Task withStatus(Status next) {
return new Task(id, title, next, priority);
}
String toLine() {
return id + "|" + status + "|" + priority + "|" + title;
}
static Task fromLine(String line, int number) {
String[] parts = line.split("[|]", 4);
if (parts.length != 4) {
throw new IllegalArgumentException("line " + number + ": expected 4 fields, got " + parts.length);
}
return new Task(Integer.parseInt(parts[0]), parts[3], Status.valueOf(parts[1]), Integer.parseInt(parts[2]));
}
}
static class Store {
private final List<Task> tasks;
private int nextId;
Store(List<Task> tasks) {
this.tasks = new ArrayList<>(tasks);
this.nextId = tasks.stream().mapToInt(Task::id).max().orElse(0) + 1;
}
Task add(String title, int priority) {
Task task = new Task(nextId++, title, Status.OPEN, priority);
tasks.add(task);
return task;
}
boolean change(int id, Status status) {
for (int i = 0; i < tasks.size(); i++) {
if (tasks.get(i).id() == id) {
tasks.set(i, tasks.get(i).withStatus(status));
return true;
}
}
return false;
}
List<Task> all() {
List<Task> sorted = new ArrayList<>(tasks);
sorted.sort(Comparator.comparingInt(Task::priority).thenComparingInt(Task::id));
return sorted;
}
List<Task> tasks() {
return tasks;
}
}
static final Path FILE = Path.of("tasks.txt");
static List<Task> load() throws IOException {
if (!Files.exists(FILE)) {
return List.of();
}
List<Task> tasks = new ArrayList<>();
List<String> lines = Files.readAllLines(FILE, StandardCharsets.UTF_8);
for (int i = 0; i < lines.size(); i++) {
if (!lines.get(i).isBlank()) {
tasks.add(Task.fromLine(lines.get(i), i + 1));
}
}
return tasks;
}
static void save(Store store) throws IOException {
List<String> lines = new ArrayList<>();
for (Task task : store.tasks()) {
lines.add(task.toLine());
}
Files.write(FILE, lines, StandardCharsets.UTF_8);
}
public static void main(String[] args) throws IOException {
if (args.length == 0) {
usage();
System.exit(2);
}
Store store = new Store(load());
try {
switch (args[0]) {
case "list" -> {
for (Task task : store.all()) {
System.out.printf("%d %-6s %d %s%n", task.id(), task.status(), task.priority(), task.title());
}
}
case "add" -> {
if (args.length != 3) {
usage();
System.exit(2);
}
Task task = store.add(args[1], Integer.parseInt(args[2]));
save(store);
System.out.println("added " + task.id());
}
case "done", "drop" -> {
if (args.length != 2) {
usage();
System.exit(2);
}
Status status = args[0].equals("done") ? Status.DONE : Status.DROPPED;
if (!store.change(Integer.parseInt(args[1]), status)) {
System.out.println("no task " + args[1]);
System.exit(1);
}
save(store);
System.out.println(args[0] + " " + args[1]);
}
default -> {
System.out.println("unknown command: " + args[0]);
usage();
System.exit(2);
}
}
} catch (IllegalArgumentException e) {
System.out.println("error: " + e.getMessage());
System.exit(1);
}
}
static void usage() {
System.out.println("usage: tasks list | add <title> <priority> | done <id> | drop <id>");
}
}
No arguments and the usage line
A program started with no word has nothing to do, so it prints one line that says how to start it and returns 2. The status is the part a shell reads, and 2 is the convention for a usage error while 1 is a failure of the work itself:
javac -Xlint:all Tasks.java
java Tasks
echo "status: $?"
usage: tasks list | add <title> <priority> | done <id> | drop <id>
status: 2
The dispatch
The first word of args is the switch of lesson 014 with strings, and each branch checks its own count. The two adds and the list are three runs against the same file, so the second add sees the first:
java Tasks add "write the report" 2
java Tasks add "read the spec" 1
java Tasks list
added 1
added 2
2 OPEN 1 read the spec
1 OPEN 2 write the report
The list is sorted by priority and not by id, which is the comparator of lesson 131: read the spec is priority 1 and comes first. The format is %d %-6s %d %s, so the id is a number, the status fills six characters, the priority is a number and the title is the rest of the line.
Exit statuses
The three failures have three statuses, and each prints a line that says what happened. The status is what a script tests, and the line is what a person reads:
java Tasks done 1
java Tasks list
java Tasks fly
java Tasks done 99
java Tasks add x 9
done 1
2 OPEN 1 read the spec
1 DONE 2 write the report
unknown command: fly
usage: tasks list | add <title> <priority> | done <id> | drop <id>
no task 99
error: priority 9 outside 1..5
The first two runs complete the task and list the file, which shows the change persisted: the second line has DONE where it was OPEN. The last three are the failures: an unknown verb prints the word and the usage line, a missing id prints the id, and a priority outside the range prints the message of the model. The first and the third return 2 and the other two return 1, as the next section of the shell shows.
The store reloaded
The last thing to see is that the store is rebuilt from the file on every run. The constructor takes the loaded list and sets the next id to the largest one plus one, so the next add after these runs is 3 and not 1. A program that kept the counter in a static field would restart it at 1 and produce two tasks with the same id.
The file is tasks.txt in the folder the program runs in, which is why the page's runs share it and the reader's do not. The class of the next lesson keeps the same model and adds an HTTP server in front of it.
Exercises
- Add a clear command that empties the file behind a confirmation word and give it a status of its own.
- Print the tasks of one status with list done and check the count of arguments.
- Make add refuse a duplicate title and read the status it returns.
- Change the order of list to the id and compare the two runs.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is
args[0]in this program?Answer
The first word after the class name
The launcher copies the words after the class into the array, one per element.
-
What does
System.exit(2)do?Answer
Ends the program at once with status 2
The status is what the shell reads, and the call does not return.
-
Why is the usage error 2 and a missing task 1?
Answer
The usage is a mistake of the caller and a missing task is a failure of the work
Two statuses let a script tell a wrong call from a task that is not there.
-
What does this program print?
public class Q1 { public static void main(String[] args) { System.out.println(args.length); for (String arg : args) { System.out.print("[" + arg + "]"); } System.out.println(); } }run asjava Q1 one two.Answer
2 / [one][two]
The two words after the class are the two elements, and the loop prints them.
-
Why does the constructor of the store look at the largest id?
Answer
So the next add after a reload does not reuse an id
The counter is rebuilt from the data, which is what a stateless run needs.
-
What does a switch on
args[0]give over a chain of ifs?Answer
One branch per verb and a default for the word that is not a verb
The string switch of lesson 014 names each command once and keeps the usage in one place.
-
Why does each branch check its own argument count?
Answer
A verb takes a different number of words, and the usage line says which
add takes two words and done one, and a wrong call is a usage error of status 2.
-
What does this program print?
public class Q2 { public static void main(String[] args) { System.out.println(args[0].equals("list") ? "listing" : "other"); System.out.println(args.length); } }run asjava Q2 list extra.Answer
listing / 2
The first word is list and the array has both words.
-
What happens to a task whose id is not in the file?
Answer
The program prints the id and returns 1
change answers false, and the branch turns that into the status of a failed work.
-
Where does the program keep the tasks between two runs?
Answer
In tasks.txt in the folder of the run
A new process has no memory of the old one, so the file is the only state.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev