Capstone: todo CLI
The first capstone is a todo list that runs from a terminal, and its whole state is one text file. Nothing in it is new: the clauses are the pattern matching of the functions lesson, the file calls are the ones of the files lesson, and the escript is the shape of the first script lesson. What is new is the assembly: a tool a reader can actually use at the end.
The file format
One task per line, an open task marked with a bracket and a space, a finished one with an x in the bracket. A line of the file looks like this:
[ ] buy milk [x] call Ada
The format is deliberately plain: a person can edit the file in any editor, and the program reads it back without a parser. The cost is that a task cannot contain a newline, which is a fair trade for a list.
The module
The module exports main/1, which is the function an escript calls with the command line as a list of strings; there is no main/0, because the tool is not started by a release but by a person. Each clause matches one command, and the last one answers a usage line:
todo.erl
-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. content/0 turns a missing file into an empty binary, which keeps the empty list out of main/1.
The escript
An escript is a file with a shebang line that the runtime runs directly. escript reads the arguments, passes the emulator flags after %%! to the VM, and calls main/1 with the arguments as strings. The wrapper is four lines, because the logic already lives in todo.erl:
todo.escript
#!/usr/bin/env escript %%! -pa . main(Args) -> todo:main(Args).
-pa . puts the folder of the script on the code path, so todo.beam is found next to it. The program above calls the escript as escript todo.escript; a release ships the same wrapper as a file with the executable bit, and then ./todo.escript works too. A build with rebar3 wraps this in the escript template of the project, and the -pa line points at the ebin folder instead of the current one.
The three commands
Compile the module and drive it through the escript. Adding is one append and no read, so the first call creates the file:
erlc todo.erl
escript todo.escript add "buy milk"
escript todo.escript add "call Ada"
Listing is the call with no arguments: it 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:
escript todo.escript
[ ] buy milk [ ] call Ada
done reads the whole file, numbers the lines and writes them back, one changed. A small file can be replaced whole; a big one would need a temporary file and a rename. A command the program does not know gets the usage line instead of a crash:
escript todo.escript done 1
escript todo.escript
[x] buy milk [ ] call Ada
escript todo.escript oops
usage: todo.escript [add Task | done N]
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/1, and that is the right answer: it is a bug in the caller, not a state the program should paper over with a message it cannot explain.
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
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 this module print?
-module(q1). -export([main/0]). main() -> io:format("~s~n", [mark(2, 2, "[ ] call Ada")]). mark(Number, Number, Line) -> "[x] " ++ rest(Line); mark(_Number, _Index, Line) -> Line. rest("[ ] " ++ Task) -> Task; rest(Line) -> Line.Answer
[x] call AdaThe equal indices match the first clause, and the prefix pattern removes the open marker before the done one is added.
-
What does this module print?
-module(q2). -export([main/0]). main() -> Lines = ["[ ] a", "[x] b"], io:format("~p~n", [length(numbered(Lines))]). numbered(Lines) -> lists:zip(lists:seq(1, length(Lines)), Lines).Answer
2lists:zip/2pairs every number with one line, so the list has one element per line. -
What does this module print?
-module(q3). -export([main/0]). main() -> ok = file:write_file("q3.txt", "one\ntwo\n"), Bin = content(), io:format("~p~n", [length(lines(Bin))]). content() -> {ok, Bin} = file:read_file("q3.txt"), Bin. lines(Bin) -> [Line || Line <- binary:split(Bin, <<"\n">>, [global]), Line =/= <<>>].Answer
2The split leaves the two words and the empty piece after the last newline, which the filter drops.
-
What does this module print?
-module(q4). -export([main/0]). main() -> ok = file:write_file("q4.txt", "x\n", [append]), ok = file:write_file("q4.txt", "y\n", [append]), {ok, Bin} = file:read_file("q4.txt"), io:format("~p~n", [Bin]).Answer
<<"x\ny\n">>The append flag keeps the first line and adds the second after it.
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.
Автор статьи: Arthur Isaev