Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,15 @@ init! = \{} -> Ok {}
respond! : Request, Model => Result Response [ServerErr Str]_
respond! = \req, _ ->
# Log request datetime, method and url
datetime = Utc.to_iso_8601 (Utc.now! {})
datetime = Utc.to_iso_8601(Utc.now!({}))

try Stdout.line! "$(datetime) $(Inspect.toStr req.method) $(req.uri)"
Stdout.line!("$(datetime) $(Inspect.toStr req.method) $(req.uri)")?

Ok {
Ok({
status: 200,
headers: [],
body: Str.toUtf8 "<b>Hello from server</b></br>",
}
})
```


Expand Down
92 changes: 46 additions & 46 deletions build.roc
Original file line number Diff line number Diff line change
Expand Up @@ -17,101 +17,101 @@ main : Task {} _
main =

cli_parser =
Arg.Opt.maybeStr { short: "p", long: "roc", help: "Path to the roc executable. Can be just `roc` or a full path." }
|> Arg.Cli.finish {
Arg.Opt.maybe_str({ short: "p", long: "roc", help: "Path to the roc executable. Can be just `roc` or a full path." })
|> Arg.Cli.finish({
name: "basic-webserver-builder",
version: "",
authors: ["Luke Boswell <https://github.com/lukewilliamboswell>"],
description: "Generates all files needed by Roc to use this basic-cli platform.",
}
|> Arg.Cli.assertValid
})
|> Arg.Cli.assert_valid

when Arg.Cli.parseOrDisplayMessage cli_parser (Arg.list! {}) is
Ok parsed_args -> run parsed_args
Err err_msg -> Task.err (Exit 1 err_msg)
when Arg.Cli.parse_or_display_message(cli_parser, Arg.list!({})) is
Ok(parsed_args) -> run(parsed_args)
Err(err_msg) -> Task.err(Exit(1, err_msg))

run : Result Str err -> Task {} _
run = \maybe_roc ->

# roc_cmd may be a path or just roc
roc_cmd = maybe_roc |> Result.withDefault "roc"
roc_cmd = maybe_roc |> Result.with_default("roc")

roc_version! roc_cmd
roc_version!(roc_cmd)

os_and_arch = get_os_and_arch!

stub_lib_path = "platform/libapp.$(stub_file_extension os_and_arch)"
stub_lib_path = "platform/libapp.$(stub_file_extension(os_and_arch))"

build_stub_app_lib! roc_cmd stub_lib_path
build_stub_app_lib!(roc_cmd, stub_lib_path)

cargo_build_host!

rust_target_folder = get_rust_target_folder!

copy_host_lib! os_and_arch rust_target_folder
copy_host_lib!(os_and_arch, rust_target_folder)

preprocess_host! roc_cmd stub_lib_path rust_target_folder
preprocess_host!(roc_cmd, stub_lib_path, rust_target_folder)

info! "Successfully built platform files!"
info!("Successfully built platform files!")

roc_version : Str -> Task {} _
roc_version = \roc_cmd ->

info! "Checking provided roc; executing `$(roc_cmd) version`:"
info!("Checking provided roc; executing `$(roc_cmd) version`:")

roc_cmd
|> Cmd.exec ["version"]
|> Task.mapErr! RocVersionCheckFailed
|> Cmd.exec(["version"])
|> Task.map_err!(RocVersionCheckFailed)

get_os_and_arch : Task OSAndArch _
get_os_and_arch =

info! "Getting the native operating system and architecture..."
info!("Getting the native operating system and architecture...")

Env.platform
|> Task.await convert_os_and_arch
|> Task.await(convert_os_and_arch)

build_stub_app_lib : Str, Str -> Task {} _
build_stub_app_lib = \roc_cmd, stub_lib_path ->

info! "Building stubbed app shared library ..."
info!("Building stubbed app shared library ...")

roc_cmd
|> Cmd.exec ["build", "--lib", "platform/libapp.roc", "--output", stub_lib_path, "--optimize"]
|> Task.mapErr! ErrBuildingAppStub
|> Cmd.exec(["build", "--lib", "platform/libapp.roc", "--output", stub_lib_path, "--optimize"])
|> Task.map_err!(ErrBuildingAppStub)

get_rust_target_folder : Task Str _
get_rust_target_folder =
when Env.var "CARGO_BUILD_TARGET" |> Task.result! is
Ok target_env_var ->
if Str.isEmpty target_env_var then
Task.ok "target/release/"
when Env.var("CARGO_BUILD_TARGET") |> Task.result! is
Ok(target_env_var) ->
if Str.is_empty(target_env_var) then
Task.ok("target/release/")
else
Task.ok "target/$(target_env_var)/release/"
Task.ok("target/$(target_env_var)/release/")

Err e ->
info! "Failed to get env var CARGO_BUILD_TARGET with error $(Inspect.toStr e). Assuming default CARGO_BUILD_TARGET (native)..."
Err(e) ->
info!("Failed to get env var CARGO_BUILD_TARGET with error $(Inspect.to_str(e)). Assuming default CARGO_BUILD_TARGET (native)...")

Task.ok "target/release/"
Task.ok("target/release/")

cargo_build_host : Task {} _
cargo_build_host =

info! "Building rust host ..."
info!("Building rust host ...")

"cargo"
|> Cmd.exec ["build", "--release"]
|> Task.mapErr! ErrBuildingHostBinaries
|> Cmd.exec(["build", "--release"])
|> Task.map_err!(ErrBuildingHostBinaries)

copy_host_lib : OSAndArch, Str -> Task {} _
copy_host_lib = \os_and_arch, rust_target_folder ->
host_build_path = "$(rust_target_folder)libhost.a"
host_dest_path = "platform/$(prebuilt_static_lib_file os_and_arch)"
host_dest_path = "platform/$(prebuilt_static_lib_file(os_and_arch))"

info! "Moving the prebuilt binary from $(host_build_path) to $(host_dest_path) ..."
info!("Moving the prebuilt binary from $(host_build_path) to $(host_dest_path) ...")
"cp"
|> Cmd.exec [host_build_path, host_dest_path]
|> Task.mapErr! ErrMovingPrebuiltLegacyBinary
|> Cmd.exec([host_build_path, host_dest_path])
|> Task.map_err!(ErrMovingPrebuiltLegacyBinary)

OSAndArch : [
MacosArm64,
Expand All @@ -125,11 +125,11 @@ OSAndArch : [
convert_os_and_arch : _ -> Task OSAndArch _
convert_os_and_arch = \{ os, arch } ->
when (os, arch) is
(MACOS, AARCH64) -> Task.ok MacosArm64
(MACOS, X64) -> Task.ok MacosX64
(LINUX, AARCH64) -> Task.ok LinuxArm64
(LINUX, X64) -> Task.ok LinuxX64
_ -> Task.err (UnsupportedNative os arch)
(MACOS, AARCH64) -> Task.ok(MacosArm64)
(MACOS, X64) -> Task.ok(MacosX64)
(LINUX, AARCH64) -> Task.ok(LinuxArm64)
(LINUX, X64) -> Task.ok(LinuxX64)
_ -> Task.err(UnsupportedNative(os, arch))

stub_file_extension : OSAndArch -> Str
stub_file_extension = \os_and_arch ->
Expand All @@ -150,13 +150,13 @@ prebuilt_static_lib_file = \os_and_arch ->

preprocess_host : Str, Str, Str -> Task {} _
preprocess_host = \roc_cmd, stub_lib_path, rust_target_folder ->
info! "Preprocessing surgical host ..."
info!("Preprocessing surgical host ...")
surgical_build_path = "$(rust_target_folder)host"

roc_cmd
|> Cmd.exec ["preprocess-host", surgical_build_path, "platform/main.roc", stub_lib_path]
|> Task.mapErr! ErrPreprocessingSurgicalBinary
|> Cmd.exec(["preprocess-host", surgical_build_path, "platform/main.roc", stub_lib_path])
|> Task.map_err!(ErrPreprocessingSurgicalBinary)

info : Str -> Task {} _
info = \msg ->
Stdout.line! "\u(001b)[34mINFO:\u(001b)[0m $(msg)"
Stdout.line!("\u(001b)[34mINFO:\u(001b)[0m $(msg)")
12 changes: 6 additions & 6 deletions examples/command.roc
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,18 @@ import pf.Utc
Model : {}

init! : {} => Result Model _
init! = \{} -> Ok {}
init! = \{} -> Ok({})

respond! : Request, Model => Result Response [CmdStatusErr _]
respond! = \req, _ ->

# Log request date, method and url using echo program
datetime = Utc.to_iso_8601 (Utc.now! {})
datetime = Utc.to_iso_8601(Utc.now!({}))

try Cmd.exec! "echo" ["$(datetime) $(Inspect.toStr req.method) $(req.uri)"]
Cmd.exec!("echo", ["$(datetime) $(Inspect.to_str(req.method)) $(req.uri)"])?

Ok {
Ok({
status: 200,
headers: [],
body: Str.toUtf8 "Command succeeded.",
}
body: Str.to_utf8("Command succeeded."),
})
28 changes: 14 additions & 14 deletions examples/dir.roc
Original file line number Diff line number Diff line change
Expand Up @@ -12,35 +12,35 @@ init! : {} => Result Model _
init! = \{} ->
# Get current working directory
cwd =
Env.cwd! {}
|> Result.mapErr? \CwdUnavailable -> Exit 1 "Unable to read current working directory"
Env.cwd!({})
|> Result.map_err?(\CwdUnavailable -> Exit(1, "Unable to read current working directory"))

try Stdout.line! "The current working directory is $(Path.display cwd)"
Stdout.line!("The current working directory is $(Path.display(cwd))")?

# Try to set cwd to examples
Env.set_cwd! (Path.from_str "examples/")
|> Result.mapErr? \InvalidCwd -> Exit 1 "Unable to set cwd to examples/"
Env.set_cwd!(Path.from_str("examples/"))
|> Result.map_err?(\InvalidCwd -> Exit(1, "Unable to set cwd to examples/"))

try Stdout.line! "Set cwd to examples/"
Stdout.line!("Set cwd to examples/")?

# List contents of examples directory
paths =
Dir.list! "./"
|> Result.mapErr? \DirErr err -> Exit 1 "Error reading directory ./:\n\t$(Inspect.toStr err)"
Dir.list!("./")
|> Result.map_err?(\DirErr(err) -> Exit(1, "Error reading directory ./:\n\t$(Inspect.to_str(err))"))

paths
|> List.map Path.display
|> Str.joinWith ","
|> List.map(Path.display)
|> Str.join_with(",")
|> \paths_str -> "The paths are;\n$(paths_str)"
|> Stdout.line!
|> try

Ok {}
Ok({})

respond! : Request, Model => Result Response []
respond! = \_, _ ->
Ok {
Ok({
status: 200,
headers: [],
body: Str.toUtf8 "Logged request",
}
body: Str.to_utf8("Logged request"),
})
14 changes: 7 additions & 7 deletions examples/echo.roc
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,19 @@ import pf.Utc
Model : {}

init! : {} => Result Model []
init! = \{} -> Ok {}
init! = \{} -> Ok({})

respond! : Request, Model => Result Response [StdoutErr _]
respond! = \req, _ ->
# Log request datetime, method and url
datetime = Utc.to_iso_8601 (Utc.now! {})
datetime = Utc.to_iso_8601(Utc.now!({}))

try Stdout.line! "$(datetime) $(Inspect.toStr req.method) $(req.uri)"
Stdout.line!("$(datetime) $(Inspect.to_str(req.method)) $(req.uri)")?

# Respond with request body
if List.isEmpty req.body then
success []
if List.is_empty(req.body) then
success([])
else
success req.body
success(req.body)

success = \body -> Ok { status: 200, headers: [], body }
success = \body -> Ok({ status: 200, headers: [], body })
22 changes: 11 additions & 11 deletions examples/env.roc
Original file line number Diff line number Diff line change
Expand Up @@ -10,29 +10,29 @@ init! : {} => Result Model [Exit I32 Str]_
init! = \{} ->

# Check if DEBUG environment variable is set
when Env.var! "DEBUG" is
Ok var if !(Str.isEmpty var) -> Ok DebugPrintMode
_ -> Ok NonDebugMode
when Env.var!("DEBUG") is
Ok(var) if !(Str.is_empty(var)) -> Ok(DebugPrintMode)
_ -> Ok(NonDebugMode)

respond! : Request, Model => Result Response [ServerErr Str]_
respond! = \_, debug ->
when debug is
DebugPrintMode ->
# Respond with all the current environment variables
vars : Dict Str Str
vars = Env.dict! {}
vars = Env.dict!({})

# Convert the Dict to a list of key-value pairs
body =
vars
|> Dict.toList
|> List.map \(k, v) -> "$(k): $(v)"
|> Str.joinWith "\n"
|> Str.concat "\n"
|> Str.toUtf8
|> Dict.to_list
|> List.map(\(k, v) -> "$(k): $(v)")
|> Str.join_with("\n")
|> Str.concat("\n")
|> Str.to_utf8

Ok { status: 200, headers: [], body }
Ok({ status: 200, headers: [], body })

NonDebugMode ->
# Respond with a message that DEBUG is not set
Ok { status: 200, headers: [], body: Str.toUtf8 "DEBUG var not set" }
Ok({ status: 200, headers: [], body: Str.to_utf8("DEBUG var not set") })
Loading
Loading