-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Expand file tree
/
Copy pathiex.ex
More file actions
526 lines (396 loc) · 15.5 KB
/
Copy pathiex.ex
File metadata and controls
526 lines (396 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
defmodule IEx do
@moduledoc ~S"""
Elixir's interactive shell.
This module is the main entry point for Interactive Elixir and
in this documentation we will talk a bit about how IEx works.
Notice that some of the functionality described here will not be available
depending on your terminal. In particular, if you get a message
saying that the smart terminal could not be run, some of the
features described here won't work.
## Helpers
IEx provides a bunch of helpers. They can be accessed by typing
`h()` into the shell or as a documentation for the `IEx.Helpers` module.
## The Break command
Inside IEx, hitting `Ctrl+C` will open up the `BREAK` menu. In this
menu you can quit the shell, see process and ets tables information
and much more.
## The User Switch command
Besides the break command, one can type `Ctrl+G` to get to the
user switch command menu. When reached, you can type `h` to
get more information.
In this menu, developers are able to start new shells and
alternate between them. Let's give it a try:
User switch command
--> s 'Elixir.IEx'
--> c
The command above will start a new shell and connect to it.
Create a new variable called `hello` and assign some value to it:
hello = :world
Now, let's roll back to the first shell:
User switch command
--> c 1
Now, try to access the `hello` variable again:
hello
** (UndefinedFunctionError) undefined function: hello/0
The command above fails because we have switched shells.
Since shells are isolated from each other, you can't access the
variables defined in one shell from the other one.
The user switch command menu also allows developers to connect to remote
shells using the `r` command. A topic which we will discuss next.
## Remote shells
IEx allows you to connect to another node in two fashions.
First of all, we can only connect to a shell if we give names
both to the current shell and the shell we want to connect to.
Let's give it a try. First start a new shell:
$ iex --sname foo
iex(foo@HOST)1>
The string in between parenthesis in the prompt is the name
of your node. We can retrieve it by calling the `node()`
function:
iex(foo@HOST)1> node()
:"foo@HOST"
iex(foo@HOST)2> Node.alive?()
true
For fun, let's define a simple module in this shell too:
iex(foo@HOST)3> defmodule Hello do
...(foo@HOST)3> def world, do: "it works!"
...(foo@HOST)3> end
Now, let's start another shell, giving it a name as well:
$ iex --sname bar
iex(bar@HOST)1>
If we try to dispatch to `Hello.world`, it won't be available
as it was defined only in the other shell:
iex(bar@HOST)1> Hello.world
** (UndefinedFunctionError) undefined function: Hello.world/0
However, we can connect to the other shell remotely. Open up
the User Switch prompt (Ctrl+G) and type:
User switch command
--> r 'foo@HOST' 'Elixir.IEx'
--> c
Now we are connected into the remote node, as the prompt shows us,
and we can access the information and modules defined over there:
rem(foo@macbook)1> Hello.world
"it works"
In fact, connecting to remote shells is so common that we provide
a shortcut via the command line as well:
$ iex --sname baz --remsh foo@HOST
Where "remsh" means "remote shell". In general, Elixir supports:
* remsh from an elixir node to an elixir node
* remsh from a plain erlang node to an elixir node (through the ^G menu)
* remsh from an elixir node to a plain erlang node (and get an erl shell there)
Connecting an Elixir shell to a remote node without Elixir is
**not** supported.
## The .iex.exs file
When starting IEx, it will look for a local `.iex.exs` file (located in the current
working directory), then a global one (located at `~/.iex.exs`) and will load the
first one it finds (if any). The code in the chosen .iex.exs file will be
evaluated in the shell's context. So, for instance, any modules that are
loaded or variables that are bound in the .iex.exs file will be available in the
shell after it has booted.
Sample contents of a local .iex.exs file:
# source another `.iex.exs` file
import_file "~/.iex.exs"
# print something before the shell starts
IO.puts "hello world"
# bind a variable that'll be accessible in the shell
value = 13
Running the shell in the directory where the above .iex.exs file is located
results in:
$ iex
Erlang 17 [...]
hello world
Interactive Elixir - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> value
13
It is possible to load another file by supplying the `--dot-iex`
option to iex. See `iex --help`.
## Configuring the shell
There are a number of customization options provided by the shell. Take a look
at the docs for the `IEx.configure/1` function by typing `h IEx.configure/1`.
Those options can be configured in your project configuration file or globally
by calling `IEx.configure/1` from your `~/.iex.exs` file like this:
# .iex.exs
IEx.configure(inspect: [limit: 3])
### now run the shell ###
$ iex
Erlang 17 (erts-5.10.1) [...]
Interactive Elixir - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> [1, 2, 3, 4, 5]
[1,2,3,...]
## Expressions in IEx
As an interactive shell, IEx evaluates expressions. This has some
interesting consequences that are worth discussing.
The first one is that the code is truly evaluated and not compiled.
This means that any benchmarking done in the shell is going to have
skewed results. So never run any profiling nor benchmarks in the shell.
Second, IEx allows you to break an expression into many lines,
since this is common in Elixir. For example:
iex(1)> "ab
...(1)> c"
"ab\nc"
In the example above, the shell will be expecting more input until it
finds the closing quote. Sometimes it is not obvious which character
the shell is expecting, and the user may find themselves trapped in
the state of incomplete expression with no ability to terminate it other
than by exiting the shell.
For such cases, there is a special break-trigger (`#iex:break`) that when
encountered on a line by itself will force the shell to break out of any
pending expression and return to its normal state:
iex(1)> ["ab
...(1)> c"
...(1)> "
...(1)> ]
...(1)> #iex:break
** (TokenMissingError) iex:1: incomplete expression
"""
@doc """
Configures IEx.
The supported options are: `:colors`, `:inspect`,
`:default_prompt`, `:alive_prompt` and `:history_size`.
## Colors
A keyword list that encapsulates all color settings used by the
shell. See documentation for the `IO.ANSI` module for the list of
supported colors and attributes.
The value is a keyword list. List of supported keys:
* `:enabled` - boolean value that allows for switching the coloring on and off
* `:eval_result` - color for an expression's resulting value
* `:eval_info` - … various informational messages
* `:eval_error` - … error messages
* `:stack_app` - … the app in stack traces
* `:stack_info` - … the remaining info in stacktraces
* `:ls_directory` - … for directory entries (ls helper)
* `:ls_device` - … device entries (ls helper)
When printing documentation, IEx will convert the markdown
documentation to ANSI as well. Those can be configured via:
* `:doc_code` — the attributes for code blocks (cyan, bright)
* `:doc_inline_code` - inline code (cyan)
* `:doc_headings` - h1 and h2 (yellow, bright)
* `:doc_title` — the overall heading for the output (reverse,yellow,bright)
* `:doc_bold` - (bright)
* `:doc_underline` - (underline)
## Inspect
A keyword list containing inspect options used by the shell
when printing results of expression evaluation. Defailt to
pretty formatting with a limit of 50 entries.
See `Inspect.Opts` for the full list of options.
## History size
Number of expressions and their results to keep in the history.
The value is an integer. When it is negative, the history is unlimited.
## Prompt
This is an option determining the prompt displayed to the user
when awaiting input.
The value is a keyword list. Two prompt types:
* `:default_prompt` - used when `Node.alive?` returns false
* `:alive_prompt` - used when `Node.alive?` returns true
The part of the listed in the following of the prompt string is replaced.
* `%counter` - the index of the history
* `%prefix` - a prefix given by `IEx.Server`
* `%node` - the name of the local node
"""
def configure(options) do
Enum.each options, fn {k, v} ->
Application.put_env(:iex, k, configure(k, v))
end
end
defp configure(k, v) when k in [:colors, :inspect] and is_list(v) do
Keyword.merge(Application.get_env(:iex, k), v)
end
defp configure(:history_size, v) when is_integer(v) do
v
end
defp configure(k, v) when k in [:default_prompt, :alive_prompt] and is_binary(v) do
v
end
defp configure(k, v) do
raise ArgumentError, "invalid configuration or value for pair #{inspect k} - #{inspect v}"
end
@doc """
Returns IEx configuration.
"""
def configuration do
Application.get_all_env(:iex)
end
@doc """
Registers a function to be invoked after the IEx process is spawned.
"""
def after_spawn(fun) when is_function(fun) do
Application.put_env(:iex, :after_spawn, [fun|after_spawn])
end
@doc """
Returns registered `after_spawn` callbacks.
"""
def after_spawn do
{:ok, list} = Application.fetch_env(:iex, :after_spawn)
list
end
@doc """
Returns `true` if IEx was started.
"""
def started? do
Application.get_env(:iex, :started, false)
end
@doc """
Returns `string` escaped using the specified `color`.
ANSI escapes in `string` are not processed in any way.
"""
def color(color, string) do
colors = Application.get_env(:iex, :colors)
if color_enabled?(colors[:enabled]) do
ansi = Keyword.get(colors, color, default_color(color))
IO.iodata_to_binary(IO.ANSI.format_fragment(ansi, true)) <> string <> IO.ANSI.reset
else
string
end
end
defp color_enabled?(nil), do: IO.ANSI.enabled?
defp color_enabled?(bool) when is_boolean(bool), do: bool
@doc """
Gets the IEx width for printing.
Used by helpers and it has a maximum cap of 80 chars.
"""
def width do
case :io.columns() do
{:ok, width} -> min(width, 80)
{:error, _} -> 80
end
end
@doc """
Gets the options used for inspecting.
"""
def inspect_opts do
Application.get_env(:iex, :inspect) ++
[width: width(), pretty: true]
end
@doc """
Pries into the process environment.
This is useful for debugging a particular chunk of code
and inspect the state of a particular process. The process
is temporarily changed to trap exits (i.e. the process flag
`:trap_exit` is set to true) and has the `group_leader` changed
to support ANSI escape codes. Those values are reverted by
calling `respawn`, which starts a new IEx shell, freeing up
the pried one.
When a process is pried, all code runs inside IEx and, as
such, it is evaluated and cannot access private functions
of the module being pried. Module functions still need to be
accessed via `Mod.fun(args)`.
## Examples
Let's suppose you want to investigate what is happening
with some particular function. By invoking `IEx.pry` from
the function, IEx will allow you to access its binding
(variables), verify its lexical information and access
the process information. Let's see an example:
import Enum, only: [map: 2]
require IEx
defmodule Adder do
def add(a, b) do
c = a + b
IEx.pry
end
end
When invoking `Adder.add(1, 2)`, you will receive a message in
your shell to pry the given environment. By allowing it,
the shell will be reset and you gain access to all variables
and the lexical scope from above:
pry(1)> map([a,b,c], &IO.inspect(&1))
1
2
3
Keep in mind that `IEx.pry` runs in the caller process,
blocking the caller during the evaluation cycle. The caller
process can be freed by calling `respawn`, which starts a
new IEx evaluation cycle, letting this one go:
pry(2)> respawn
true
Interactive Elixir - press Ctrl+C to exit (type h() ENTER for help)
Setting variables or importing modules in IEx does not
affect the caller the environment (hence it is called `pry`).
"""
defmacro pry(timeout \\ 1000) do
quote do
env = __ENV__
meta = "#{inspect self} at #{Path.relative_to_cwd(env.file)}:#{env.line}"
opts = [binding: binding, dot_iex_path: "", env: env, prefix: "pry"]
res = IEx.Server.take_over("Request to pry #{meta}", opts, unquote(timeout))
# We cannot use colors because IEx may be off.
case res do
{:error, :self} = err ->
IO.puts :stdio, "IEx cannot pry itself."
{:error, :no_iex} = err ->
IO.puts :stdio, "Cannot pry #{meta}. Is an IEx shell running?"
_ ->
:ok
end
res
end
end
## Callbacks
# This is a callback invoked by Erlang shell utilities
# when someone press Ctrl+G and adds 's Elixir.IEx'.
@doc false
def start(opts \\ [], mfa \\ {IEx, :dont_display_result, []}) do
spawn fn ->
case :init.notify_when_started(self()) do
:started -> :ok
_ -> :init.wait_until_started()
end
:ok = start_iex()
:ok = set_expand_fun()
:ok = run_after_spawn()
IEx.Server.start(opts, mfa)
end
end
@doc false
def dont_display_result, do: :"do not show this result in output"
## Helpers
defp start_iex() do
unless started? do
{:ok, _} = Application.ensure_all_started(:iex)
Application.put_env(:iex, :started, true)
end
:ok
end
defp set_expand_fun do
gl = Process.group_leader
glnode = node gl
expand_fun =
if glnode != node do
_ = ensure_module_exists glnode, IEx.Remsh
IEx.Remsh.expand node
else
&IEx.Autocomplete.expand(&1)
end
# expand_fun is not supported by a shell variant
# on Windows, so we do two io calls, not caring
# about the result of the expand_fun one.
_ = :io.setopts(gl, expand_fun: expand_fun)
:io.setopts(gl, binary: true, encoding: :unicode)
end
defp ensure_module_exists(node, mod) do
unless :rpc.call node, :code, :is_loaded, [mod] do
{m, b, f} = :code.get_object_code mod
{:module, _} = :rpc.call node, :code, :load_binary, [m, f, b]
end
end
defp run_after_spawn do
_ = for fun <- Enum.reverse(after_spawn), do: fun.()
:ok
end
# Used by default on evaluation cycle
defp default_color(:eval_interrupt), do: [:yellow]
defp default_color(:eval_result), do: [:yellow]
defp default_color(:eval_error), do: [:red]
defp default_color(:eval_info), do: [:normal]
defp default_color(:stack_app), do: [:red, :bright]
defp default_color(:stack_info), do: [:red]
# Used by ls
defp default_color(:ls_directory), do: [:blue]
defp default_color(:ls_device), do: [:green]
# Used by ansi docs
defp default_color(:doc_bold), do: [:bright]
defp default_color(:doc_code), do: [:cyan, :bright]
defp default_color(:doc_headings), do: [:yellow, :bright]
defp default_color(:doc_inline_code), do: [:cyan]
defp default_color(:doc_underline), do: [:underline]
defp default_color(:doc_title), do: [:reverse, :yellow, :bright]
end