Capstone: todo CLI
The data file
The capstone is a todo list in the spirit of lessons 24 and 37: one task per line in todo.txt, an open task marked with three characters and a space, a finished one with an x in the box. Nothing else is stored, so the file stays readable and editable by hand. Save this module as todo.erl; main/1 is the same function an escript calls, and each clause matches one shape of the argument list.
-module(todo).
-export([main/1]).
-define(STORE, "todo.txt").
main(["add", Task]) ->
ok = file:write_file(?STORE, ["[ ] ", Task, "\n"], [append]);
main(["done", N]) ->
Number = list_to_integer(N),
ok = file:write_file(?STORE, [[mark(Number, Index, Line), "\n"]
|| {Index, Line} <- numbered(lines())]);
main([]) ->
io:format("~s", [content()]);
main(_) ->
io:format("usage: todo.escript [add Task | done N]~n").
content() ->
case file:read_file(?STORE) of
{ok, Bin} ->
Bin;
{error, enoent} ->
<<>>
end.
lines() ->
[binary_to_list(Line)
|| Line <- binary:split(content(), <<"\n">>, [global]),
Line =/= <<>>].
numbered(Lines) ->
lists:zip(lists:seq(1, length(Lines)), Lines).
mark(Number, Number, Line) ->
"[x] " ++ rest(Line);
mark(_Number, _Index, Line) ->
Line.
rest("[ ] " ++ Task) ->
Task;
rest(Line) ->
Line.
Two details carry the program. mark/3 repeats the first argument in the second position, so the clause only matches when the wanted number is the current index. rest/1 uses a prefix pattern, so a line that is already done keeps its text instead of losing its marker twice.
Add a task
Adding is one append and no read: the open flag list does the work, and the file is created on the first call. The shell below drives main/1 exactly as the command line does, argument list and all. Save the module, compile it, and start a shell.
erlc todo.erl
erl
1> todo:main([]).
ok
2> todo:main(["add", "buy milk"]).
ok
3> todo:main(["add", "call Ada"]).
ok
The first call prints nothing, because the file does not exist yet and content/0 answers an empty binary for that case. An empty answer is the right one for an empty list, and it keeps the code free of a special case in main/1.
List tasks
With no arguments the clause reads the file into a binary and prints it as text. ~s writes the bytes and adds nothing, so the output is the file itself.
erl
1> todo:main([]).
[ ] buy milk
[ ] call Ada
ok
The ok at the end is the return value of the io:format call, not a line of the file. The escript of the next section does not show it, because an escript prints nothing but what the program prints.
Mark done
done reads the whole file, numbers the lines and writes them back, one changed. That is the rewrite pattern of lesson 37: small files can be replaced whole, and a big file would need a temporary file and a rename.
erl
1> todo:main(["done", "1"]).
ok
2> todo:main([]).
[x] buy milk
[ ] call Ada
ok
3> todo:main(["oops"]).
usage: todo.escript [add Task | done N]
ok
The last clause is the one that catches everything else, so a typo gets a usage line instead of a function clause crash. An argument that matches a clause but has a bad value, such as done with a word instead of a number, still crashes in list_to_integer, and that is fine: it is a bug in the caller, not a state the program should paper over.
The escript wrapper
An escript is a file with a shebang line that the Erlang runtime runs directly. escript reads the arguments, ignores the %%! line of emulator flags, and calls main/1 with the list of arguments as strings. The whole wrapper is three lines, because the logic already lives in todo.erl. Save it as todo.escript next to the beam file.
#!/usr/bin/env escript
%%! -pa .
main(Args) ->
todo:main(Args).
chmod +x todo.escript
./todo.escript add "buy milk"
./todo.escript add "call Ada"
Neither call prints anything: adding a task writes the file and says nothing, because an escript shows only what the program writes. Listing is the command with output.
./todo.escript
[ ] buy milk
[ ] call Ada
./todo.escript done 1
./todo.escript
[x] buy milk
[ ] call Ada
The done call is silent again, and the last listing shows the changed marker. A real build would ship the escript with rebar3 and the escript template, and the -pa flag would point at the ebin folder of the release.
Next: Capstone: TCP server
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
main/1of an escript receive?Answer
The arguments as a list of strings
escript turns the command line into a list of strings and calls
main/1with it. -
Why does
main(["add", Task])use a list pattern?Answer
To select the clause by the shape of the command line
Each clause matches one command, and the variable Task takes the second word.
-
What does
[append]do in the add clause?Answer
Adds the task to the end of the file
The append flag writes at the end and creates the file when it is missing.
-
What does
content/0answer for a missing file?Answer
An empty binary
The
{error, enoent}clause answers<<>>, so an empty list prints nothing. -
What does
mark(Number, Number, Line)match?Answer
Only the line whose index equals the wanted number
Repeating the variable in the second position forces the two values to be equal.
-
What does
rest("[ ] " ++ Task)do?Answer
Removes the open marker and keeps the text
The prefix pattern splits the marker off, and
mark/3puts the done marker in front. -
How does
donewrite the file back?Answer
It rewrites the whole file with the changed line
Small files are read whole, changed in memory and written back in one call.
-
What does
io:format("~s", [Content])add to the output?Answer
Nothing: it prints the bytes
The format string has no
~n, so the file content appears exactly as stored. -
What does the
%%!line of an escript hold?Answer
Emulator flags for the run
escript passes the flags after
%%!to the emulator, such as-pa .. -
What does an escript print for a call that returns
ok?Answer
Nothing
Unlike the shell, an escript prints only what the program writes itself.
The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev