Skip to content

Commit c2b3e05

Browse files
migrate command line example and test
1 parent 5779c84 commit c2b3e05

File tree

2 files changed

+17
-43
lines changed

2 files changed

+17
-43
lines changed

ci/expect_scripts/command-line-args.exp

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,11 @@
55

66
set timeout 7
77

8-
spawn $env(EXAMPLES_DIR)/command-line-args foo
9-
108
source ./ci/expect_scripts/shared-code.exp
119

10+
spawn $env(EXAMPLES_DIR)/command-line-args foo
1211

13-
set expected_output [normalize_output {
14-
received argument: foo
15-
Unix argument, bytes: \[102, 111, 111\]
16-
back to Arg: "foo"
17-
}]
18-
19-
expect $expected_output {
12+
expect "received argument: foo\r\n" {
2013
expect eof {
2114
check_exit_and_segfault
2215
}

examples/command-line-args.roc

Lines changed: 15 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,18 @@
1-
app [main!] {
2-
pf: platform "../platform/main.roc",
3-
}
1+
app [main!] { pf: platform "../platform/main.roc" }
42

53
import pf.Stdout
6-
import pf.Arg exposing [Arg]
7-
8-
# How to handle command line arguments in Roc.
9-
10-
# To run this example: check the README.md in this folder
11-
12-
main! : List Arg => Result {} _
13-
main! = |raw_args|
14-
15-
# get the second argument, the first is the executable's path
16-
when List.get(raw_args, 1) |> Result.map_err(|_| ZeroArgsGiven) is
17-
Err(ZeroArgsGiven) ->
18-
Err(Exit(1, "Error ZeroArgsGiven:\n\tI expected one argument, but I got none.\n\tRun the app like this: `roc main.roc -- input.txt`"))
194

20-
Ok(first_arg) ->
21-
Stdout.line!("received argument: ${Arg.display(first_arg)}")?
22-
23-
# # OPTIONAL TIP:
24-
25-
# If you ever need to pass an arg to a Roc package, it will probably expect an argument with the type `[Unix (List U8), Windows (List U16)]`.
26-
# You can convert an Arg to that with `Arg.to_os_raw`.
27-
#
28-
# Roc packages like to be platform agnostic so that everyone can use them, that's why they avoid platform-specific types like `pf.Arg`.
29-
when Arg.to_os_raw(first_arg) is
30-
Unix(bytes) ->
31-
Stdout.line!("Unix argument, bytes: ${Inspect.to_str(bytes)}")?
32-
33-
Windows(u16s) ->
34-
Stdout.line!("Windows argument, u16s: ${Inspect.to_str(u16s)}")?
35-
36-
# You can go back with Arg.from_os_raw:
37-
Stdout.line!("back to Arg: ${Inspect.to_str(Arg.from_os_raw(Arg.to_os_raw(first_arg)))}")
5+
main! : List(Str) => Try({}, [Exit(I32)])
6+
main! = |args| {
7+
# Skip first arg (executable path), get the remaining args
8+
match args.drop_first(1) {
9+
[first_arg, ..] => {
10+
Stdout.line!("received argument: ${first_arg}")
11+
Ok({})
12+
}
13+
[] => {
14+
Stdout.line!("Error: I expected one argument, but got none.")
15+
Err(Exit(1))
16+
}
17+
}
18+
}

0 commit comments

Comments
 (0)