on 4fdc19d help sign in
urbit.org/content/docs/hoon/guides/cli-tutorial.md
440 lines 16 kB history raw
1+++
2title = "CLI apps"
3weight = 2
4template = "doc.html"
5+++
7## Introduction
9In this walkthrough we will go in-depth on how to build command line interface (CLI)
10applications in Urbit using the `shoe` library.
12There are three CLI apps that currently ship with urbit - `%dojo`, `%chat-cli`,
13and `%shoe`. You should be familiar with the former two, the latter is an
14example app that shows off how the `shoe` library works that we will be looking
15at closely. These are all Gall apps, and their source can be found in the `app/`
16folder of your `%base` desk.
18In [the `shoe` library](#the-shoe-library) we take a closer look at the `shoe` library and its
19cores and how they are utilized in CLI apps. Then in [the `sole`
20library](#the-sole-library) we look at what `shoe` effects ultimately break down
21into. Finally in [`%shoe` app walkthrough](#shoe-app-walkthrough) we explore
22the functionality of the `%shoe` app and then go through the code line-by-line.
24This tutorial can be
25considered to be an application equivalent of the [Hoon school
26lesson](/docs/hoon/hoon-school/generators#ask) on `sole` and `%ask`
27generators, which only covers the bare minimum necessary to write generators
28that take user input.
30## The `shoe` library {#the-shoe-library}
32Here we describe how sessions are identified, the specialized `card`s that Gall agents
33with the `shoe` library are able to utilize, and the different cores of `/lib/shoe.hoon` and their purpose.
35### Session identifiers
37An app using the `shoe` library will automatically track sessions by their `sole-id=@ta`.
38These are opaque identifiers generated by the connecting client. An app using the `shoe`
39library may be connected to by a local or remote ship in order to send commands,
40and each of these connections is assigned a unique `@ta` that identifies the
41ship and which session on that ship if there are multiple.
43### `%shoe` `card`s
45Gall agents with the `shoe` library are able to utilize `%shoe` `card`s. These
46additions to the standard set of `cards` have the following shape:
48```hoon
49[%shoe sole-ids=(list @ta) effect=shoe-effect]`
50```
52`sole-ids` is the `list` of session ids that the following `effect` is
53emitted to. An empty `sole-ids` sends the effect to all connected sessions.
54`shoe-effect`s, for now, are always of the shape `[%sole effect=sole-effect]`, where
55`sole-effect`s are basic console events such as displaying text, changing the
56prompt, beeping, etc. These are described in the section on the [`sole` library](#the-sole-library).
58For example, a `%shoe` `card` that causes all connected sessions to beep would
59be `[%shoe ~ %sole %bel ~]`.
61### `shoe` core
63An iron (contravariant) door that defines an interface for Gall agents utilizing
64the `shoe` library. Use this core whenever you want to receive input from the user and run a command. The input will get
65put through the parser (`+command-parser`) and results in a noun of
66`command-type` that the underlying application specifies, which shoe then feeds back into the underlying app as an `+on-command` callback.
68In addition to the ten arms that all Gall core apps possess, `+shoe` defines and expects a few
69more, tailored to common CLI logic. Thus you will need to wrap the `shoe:shoe` core using the `agent:shoe` function to obtain a standard
7010-arm Gall agent core. See the [shoe example app
71walkthrough](#shoe-example-app-walkthrough) for how to do this.
73The additional arms are described below. The Hoon code shows their expected type signature. As we'll see [later](#shoe-app-walkthrough), the `command-type` can differ per application. Note also that most of these take a session identifier as an argument. This lets applications provide different users (at potentially different "places" within the application) with different affordances.
75#### `+command-parser`
77```hoon
78 ++ command-parser
79 |~ sole-id=@ta
80 |~(nail *(like [? command-type]))
81```
83Input parser for a specific command-line session. Will be run on whatever the user tries to input into the command prompt, and won't let them type anything that doesn't parse. If the head of the result is true,
84instantly run the command. If it's false, require the user to press return.
86#### `+tab-list`
88```hoon
89 ++ tab-list
90 |~ sole-id=@ta
91 *(list (option:auto tank))
92```
94Autocomplete options for the command-line session (to match `+command-parser`).
96#### `+on-command`
98```hoon
99 ++ on-command
100 |~ [sole-id=@ta command=command-type]
101 *(quip card _this)
102```
104Called when a valid command is run.
106#### `+can-connect`
108```hoon
109 ++ can-connect
110 |~ sole-id=@ta
111 *?
112```
114Called to determine whether a session may be opened or connected to. For example, you
115may only want the local ship to be able to connect.
117#### `+on-connect`
119```hoon
120 ++ on-connect
121 |~ sole-id=@ta
122 *(quip card _^|(..on-init))
123```
125Called when a session is opened or connected to.
127#### `+on-disconnect`
129```hoon
130 ++ on-disconnect
131 |~ sole-id=@ta
132 *(quip card _^|(..on-init))
133```
135Called when a previously made session gets disconnected from.
137### `default` core
139This core contains the bare minimum implementation of the additional `shoe` arms
140beyond the 10 standard Gall app ams. It is used
141analogously to how the `default-agent` core is used for regular Gall apps.
143### `agent` core
145This is a function for wrapping a `shoe` core, which has too many
146arms to be a valid Gall agent core. This turns it into a standard Gall agent core by
147integrating the additional arms into the standard ones.
149## The `sole` library {#the-sole-library}
151`shoe` apps may create specialized `card`s of the `[%shoe (list @ta) shoe-effect]` shape, where `shoe-effect` currently just wrap `sole-effect`s, i.e. instructions for displaying text and producing other effects in the console.
153The list of possible `sole-effects` can be found in `/sur/sole.hoon`. A few
154commonly used ones are as follows.
156- `[%txt tape]` is used to display a line of text.
157- `[%bel ~]` is used to emit a beep.
158- `[%pro sole-prompt]` is used to set the prompt.
159- `[%mor (list sole-effect)]` is used to emit multiple effects.
161For example, a `sole-effect` that beeps and displays `This is some text.` would
162be structured as
164```hoon
165[%mor [%txt "This is some text."] [%bel ~] ~]
166```
168## `%shoe` app walkthrough {#shoe-app-walkthrough}
170Here we explore the capabilities of the `%shoe` example app and then go through
171the code, explaining what each line does.
173### Playing with `%shoe`
175First let's test the functionality of `%shoe` so we know what we're getting
176into.
178Start two fake ships, one named `~zod` and the other can have any name - we will
179go with `~nus`. Fake ships run locally are able to see each other, and our
180intention is to connect their `%shoe` apps.
182On each fake ship start `%shoe` by entering `|start %shoe` into dojo. This will
183automatically
184change the prompt to `~zod:shoe>` and `~nus:shoe>`. Type `demo` and watch the following appear:
186```
187~zod ran the command
188~zod:shoe>
189```
191`~zod ran the command` should be displayed in bold green text, signifying that
192the command originated locally.
194Now we will connect the sessions. Switch `~zod` back to dojo with `Ctrl-X` and enter `|link ~nus %shoe`. If this succeeds you will see the following.
196```
197>=
198; ~nus is your neighbor
199[linked to [p=~nus q=%shoe]]
200```
202Now `~zod` will have two `%shoe` sessions running - one local one on `~zod` and
203one remote one on `~nus`, which you can access by pressing `Ctrl-X` until you see
204`~nus:shoe>` from `~zod`'s console. On the other hand, you should not see
205`~zod:shoe>` on `~nus`'s side, since you have not connected `~nus` to `~zod`'s
206`%shoe` app. When you enter `demo` from `~nus:shoe>` on
207`~zod`'s console you will again see `~zod ran the command`, but this time it
208should be in the ordinary font used by the console, signifying that the command
209is originating from a remote session. Contrast this with entering `demo` from
210`~nus:shoe>` in `~nus`'s console, which will display `~nus ran the command` in
211bold green text.
213Now try to link to `~zod`'s `%shoe` session from `~nus` by switching to the dojo
214on `~nus` and entering `|link ~zod %shoe`. You should see
216```
217>=
218[unlinked from [p=~zod q=%shoe]]
219```
221and if you press `Ctrl-X` you will not get a `~zod:shoe>` prompt. This is
222because the example app is set up to always allow `~zod` to connect (as well as
223subject moons if the ship happens to be a planet) but not `~nus`, so this
224message means that `~nus` failed to connect to `~zod`'s `%shoe` session.
226### `%shoe`'s code
228```hoon
229:: shoe: example usage of /lib/shoe
230::
231:: the app supports one command: "demo".
232:: running this command renders some text on all sole clients.
233::
234/+ shoe, verb, dbug, default-agent
235```
237`/+` is the Ford rune which imports libraries from the `/lib` directory into
238the subject.
240- `shoe` is the `shoe` library.
241- `verb` is a library used to print what a Gall agent is doing.
242- `dbug` is a library of debugging tools.
243- `default-agent` contains a Gall agent core with minimal implementations of
244 required Gall arms.
246```hoon
247|%
248+$ state-0 [%0 ~]
249+$ command ~
250::
251+$ card card:shoe
252--
253```
255The types used by the app.
257`state-0` stores the state of the app, which is null as there is no state to
258keep track of. It is good practice to include a version number anyways,
259in case the app is made stateful at a later time.
261`command` is typically a set of tagged union types that represent the possible
262commands that can be entered by the user. Since this app only supports one
263command, it is unnecessary for it to have any associated data, thus the command
264is represented by `~`.
266In a non-trivial context, a `command` is commonly given by `[%name data]`, where `%name` is the identifier for the type of command and `data` is
267a type or list of types that contain data needed to execute the command. See
268`app/chat-cli.hoon` for examples of commands, such as `[%say letter:store]` and
269`[%delete path]`. This is not required though, and you could use something like
270`[chat-room=@t =action]`.
272`card` is either an ordinary Gall agent `card` or a `%shoe` `card`, which takes
273the shape `[%shoe sole-ids=(list @ta) effect=shoe-effect]`. A `%shoe` `card` is
274sent to all `sole`s listed in `sole-ids`, imaking them run the `sole-effect`
275specified by `effect` (i.e. printing some text). Here we can
276reference `card:shoe` because of `/+ shoe` at the beginning of the app.
278```hoon
279=| state-0
280=* state -
281::
282```
284Add the bunt value of `state-0` to the head of the subject, then give it the
285macro `state`. The `-` here is a lark expression referring to the head of the
286subject. This allows us to use `state` to refer to the state elsewhere in the
287code no matter what version we're using, while also getting direct access to the
288contents of `state` (if it had any).
290```hoon
291%+ verb |
292%- agent:dbug
293^- agent:gall
294%- (agent:shoe command)
295^- (shoe:shoe command)
296```
298The casts here are just reminders of what is being produced. So let's focus on
299what the `%` runes are doing, from bottom to top. We call `(agent:shoe command)`
300on what follows (i.e. the rest of the app),
301producing a standard Gall agent core. Then we call wrap the Gall agent core with
302`agent:dbug`, endowing it with additional arms useful for debugging, and then
303wrap again with `verb`.
305```hoon
306|_ =bowl:gall
307+* this .
308 def ~(. (default-agent this %|) bowl)
309 des ~(. (default:shoe this command) bowl)
310```
312This is boilerplate Gall agent core code. We set `this` to be a macro for the
313subject, which is the Gall agent core itself. We set `def` and `des` to be
314macros for initialized `default-agent` and `default:shoe` doors respectively.
316Next we implement all of the arms required for a `shoe` agent. Starting with
317the standard Gall arms:
319```hoon
320++ on-init on-init:def
321++ on-save !>(state)
322++ on-load
323 |= old=vase
324 ^- (quip card _this)
325 [~ this]
326::
327++ on-poke on-poke:def
328++ on-watch on-watch:def
329++ on-leave on-leave:def
330++ on-peek on-peek:def
331++ on-agent on-agent:def
332++ on-arvo on-arvo:def
333++ on-fail on-fail:def
334```
336These are minimalist Gall app arm implementations using the default behavior found in `def`.
338Here begins the implementation of the additional arms required by the
339`(shoe:shoe command)` interface.
341```hoon
342++ command-parser
343 |= sole-id=@ta
344 ^+ |~(nail *(like [? command]))
345 (cold [& ~] (jest 'demo'))
346```
348`+command-parser` is of central importance - it is what is used to parse user
349input and transform it into `command`s for the app to execute. Writing a proper
350command parser requires understanding of the Hoon parsing functions found in the
351standard library. How to do so may be found in the [parsing tutorial](/docs/hoon/guides/parsing). For now, it is sufficient to know that this arm matches the text "demo" and
352produces a `[? command]`-shaped noun in response. Note how the `&` signifies that the command will be run as soon as it has been entered, without waiting for the user to press return.
354```hoon
355++ tab-list
356 |= sole-id=@ta
357 ^- (list [@t tank])
358 :~ ['demo' leaf+"run example command"]
359 ==
360```
362`+tab-list` is pretty much plug-n-play. For each command you want to be tab
363completed, add an entry to the `list` begun by `:~` of the form `[%command leaf+"description"]`. Now whenever the user types a partial command and presses
364tab, the console will display the list of commmands that match the partial
365command as well as the descriptions given here.
367Thus here we have that starting to type `demo` and pressing tab will result in
368the following output in the console:
370```
371demo run example command
372~zod:shoe> demo
373```
375with the remainder of `demo` now added to the input line.
377Next we have `+on-command`, which is called whenever `+command-parser`
378recognizes that `demo` has been entered by a user.
380```hoon
381++ on-command
382 |= [sole-id=@ta =command]
383 ^- (quip card _this)
384```
386This is a gate that takes in the `sole-id` corresponding to the session and the
387`command` noun parsed by `+command-parser` and returns a `list` of `card`s and
388`_this`, which is our shoe agent core including its state.
390```hoon
391 =- [[%shoe ~ %sole -]~ this]
392```
394This creates a cell of a `%shoe` card that triggers a `sole-effect` given by the head of
395the subject `-`, then the Gall agent core `this` - i.e. the return result of
396this gate. The use of the `=-` rune means that what follows this
397expression is actually run first, which puts the desired `sole-effect` into the
398head of the subject.
400```hoon
401 =/ =tape "{(scow %p src.bowl)} ran the command"
402```
404We define the `tape` that we want to be printed.
406```hoon
407 ?. =(src our):bowl
408 [%txt tape]
409 [%klr [[`%br ~ `%g] [(crip tape)]~]~]
410```
412We cannot just produce the `tape` we want printed, - it needs to fit the
413`sole-effect` type. This tells us that if the
414origin of the command is not our ship to just print it normally with the `%txt`
415`sole-effect`. Otherwise we use `%klr`, which prints it stylistically (here it
416makes the text green and bold).
418The following allows either `~zod`, or the host ship and its moons, to connect to
419this app's command line interface using `|link`.
421```hoon
422++ can-connect
423 |= sole-id=@ta
424 ^- ?
425 ?| =(~zod src.bowl)
426 (team:title [our src]:bowl)
427 ==
428```
430We use the minimal implementations for the final two `shoe` arms, since we don't
431want to do anything special when users connect or disconnect.
433```hoon
434++ on-connect on-connect:des
435++ on-disconnect on-disconnect:des
436--
437```
439This concludes our review of the code of the `%shoe` app. To continue learning
440how to build your own CLI app, we recommend checking out `/app/chat-cli.hoon`.