Code Whisperer
Code Whisperer

Reputation: 23652

PureScript - Pass arguments to main using the command line

PureScript programs export a main function which is invoked when you run the program. But it's unclear how to pass arguments to it, or if that is possible.

Consider the following simple program, which capitalizes a string.

module Main where

import Effect (Effect)
import Effect.Console (log)
import Prelude (Unit, discard)

import Data.String (toUpper)

message :: String 
message = "Satisfaction Rating: 8.23"

main ∷ Effect Unit
main = do
  log ( toUpper ( message ) )

Which outputs

SATISFACTION RATING: 8.23

This program is executed when spago run is invoked.

My question is as follows: How can the argument message in the code example, be passed in via the command line, creating a custom message capitalizer?

The updated run command would look something like:

spago run --message="new_message"

And the updated output would look like

NEW_MESSAGE

In short, how do you pass values to a PureScript program from outside?

Upvotes: 1

Views: 525

Answers (1)

Fyodor Soikin
Fyodor Soikin

Reputation: 80744

When you execute a PureScript program with spago run, it runs under Node. Therefore, to get command-line arguments, you need to as Node.

And look: there is a PureScript binding for the relevant Node facilities - the argv function from purescript-node-process. It's an effect that returns an array of arguments:

import Node.Process (argv)

main = do
  args <- argv
  log $ show args

A quick examination of spago run --help reveals that arguments can be passed to the program via the -b parameter:

spago run -b somearg

For multiple arguments, quote them:

spago run -b "somearg anotherarg"

Note that this works on Linux (and presumably macOS), but fails on Windows, where Spago for some reason ignores the quotes and tries to interpret anotherarg as its own argument. This is clearly a bug. This issue seems relevant.

Upvotes: 4

Related Questions