Safe Haskell | None |
---|---|
Language | Haskell2010 |
Embelish a Haskell command-line program with useful behaviours.
Runtime
Sets number of capabilities (heavy-weight operating system threads used by the GHC runtime to run Haskell green threads) to the number of CPU cores available (for some reason the default is 1 capability only, which is a bit silly on a multicore system).
Install signal handlers to properly terminate the program performing cleanup as necessary.
Encoding is set to UTF-8, working around confusing bugs that sometimes occur when applications are running in Docker containers.
Logging and output
The Program
monad provides functions for both normal output and debug
logging. A common annoyance when building command line tools and daemons is
getting program output to stdout
and debug messages interleaved, made
even worse when error messages written to stderr
land in the same
console. To avoid this, when all output is sent through a single channel.
This includes both normal output and log messages.
Exceptions
Ideally your code should handle (and not leak) exceptions, as is good
practice anywhere in the Haskell ecosystem. As a measure of last resort
however, if an exception is thrown (and not caught) by your program it will
be caught at the outer execute
entrypoint, logged for debugging, and then
your program will exit.
Customizing the execution context
The execute
function will run your Program
in a basic Context
initialized with appropriate defaults. Most settings can be changed at
runtime, but to specify the allowed command-line options and expected
arguments you can initialize your program using configure
and then run
with executeWith
.
Synopsis
- data Program τ α
- configure :: Version -> τ -> Config -> IO (Context τ)
- execute :: Program None α -> IO ()
- executeWith :: Context τ -> Program τ α -> IO ()
- terminate :: Int -> Program τ α
- getCommandLine :: Program τ Parameters
- lookupOptionFlag :: LongName -> Parameters -> Maybe Bool
- lookupOptionValue :: LongName -> Parameters -> Maybe String
- lookupArgument :: LongName -> Parameters -> Maybe String
- lookupEnvironmentValue :: LongName -> Parameters -> Maybe String
- getProgramName :: Program τ Rope
- setProgramName :: Rope -> Program τ ()
- setVerbosityLevel :: Verbosity -> Program τ ()
- getConsoleWidth :: Program τ Int
- getApplicationState :: Program τ τ
- setApplicationState :: τ -> Program τ ()
- outputEntire :: Handle -> Bytes -> Program τ ()
- inputEntire :: Handle -> Program τ Bytes
- execProcess :: [Rope] -> Program τ (ExitCode, Rope, Rope)
- data Thread α
- forkThread :: Program τ α -> Program τ (Thread α)
- sleepThread :: Rational -> Program τ ()
- resetTimer :: Program τ ()
- waitThread :: Thread α -> Program τ α
- waitThread_ :: Thread α -> Program τ ()
- trap_ :: Program τ α -> Program τ ()
- data Context τ
- data None = None
- invalid :: Program τ α
- data Boom = Boom
Documentation
The type of a top-level program.
You would use this by writing:
module Main where import Core.Program main ::IO
() main =execute
program
and defining a program that is the top level of your application:
program ::Program
None
()
Such actions are combinable; you can sequence them (using bind in do-notation) or run them in parallel, but basically you should need one such object at the top of your application.
Type variables
A Program
has a user-supplied application state and a return type.
The first type variable, τ
, is your application's state. This is an object
that will be threaded through the computation and made available to your code
in the Program
monad. While this is a common requirement of the outer code
layer in large programs, it is often not necessary in small programs or when
starting new projects. You can mark that there is no top-level application
state required using None
and easily change it later if your needs evolve.
The return type, α
, is usually unit as this effectively being called
directly from main
and Haskell programs have type
. That is, they
don't return anything; I/O having already happened as side effects.IO
()
Programs in separate modules
One of the quirks of Haskell is that it is difficult to refer to code in the
Main module when you've got a number of programs kicking around in a project
each with a main
function. One way of dealing with this is to put your
top-level Program
actions in a separate modules so you can refer to them
from test suites and example snippets.
Interoperating with the rest of the Haskell ecosystem
The Program
monad is a wrapper over IO
; at any point when you need to move
to another package's entry point, just use liftIO
. It's re-exported by
Core.System.Base for your convenience. Later, you might be interested in
unlifting back to Program; see Core.Program.Unlift.
Instances
Monad (Program τ) Source # | |
Functor (Program τ) Source # | |
Applicative (Program τ) Source # | |
MonadIO (Program τ) Source # | |
Defined in Core.Program.Context | |
MonadThrow (Program τ) Source # | |
Defined in Core.Program.Context | |
MonadCatch (Program τ) Source # | |
MonadMask (Program t) Source # | |
Defined in Core.Program.Context | |
MonadReader (Context τ) (Program τ) Source # | |
Running programs
configure :: Version -> τ -> Config -> IO (Context τ) Source #
Initialize the programs's execution context. This takes care of various administrative actions, including setting up output channels, parsing command-line arguments (according to the supplied configuration), and putting in place various semaphores for internal program communication. See Core.Program.Arguments for details.
This is also where you specify the initial {blank, empty, default) value for
the top-level user-defined application state, if you have one. Specify None
if you aren't using this feature.
execute :: Program None α -> IO () Source #
Embelish a program with useful behaviours. See module header
Core.Program.Execute for a detailed description. Internally this function
calls configure
with an appropriate default when initializing.
executeWith :: Context τ -> Program τ α -> IO () Source #
Embelish a program with useful behaviours, supplying a configuration for command-line options & argument parsing and an initial value for the top-level application state, if appropriate.
Exiting a program
terminate :: Int -> Program τ α Source #
Safely exit the program with the supplied exit code. Current output and debug queues will be flushed, and then the process will terminate.
Accessing program context
getCommandLine :: Program τ Parameters Source #
Retrieve the values of parameters parsed from options and arguments supplied by the user on the command-line.
The command-line parameters are returned in a Map
, mapping from from the
option or argument name to the supplied value. You can query this map
directly:
program = do params <-getCommandLine
let result =lookupKeyValue
"silence" (paramterValuesFrom params) case result ofNothing
->return
()Just
quiet = case quiet ofValue
_ ->throw
NotQuiteRight -- complain that flag doesn't take valueEmpty
->write
"You should be quiet now" -- much better ...
which is pattern matching to answer "was this option specified by the user?" or "what was the value of this [mandatory] argument?", and then "if so, did the parameter have a value?"
This is available should you need to differentiate between a Value
and an
Empty
ParameterValue
, but for many cases as a convenience you can use the
lookupOptionFlag
, lookupOptionValue
, and lookupArgument
functions below
(which are just wrappers around a code block like the example shown here).
lookupOptionFlag :: LongName -> Parameters -> Maybe Bool Source #
Returns Just True
if the option is present, and Nothing
if it is not.
lookupOptionValue :: LongName -> Parameters -> Maybe String Source #
Look to see if the user supplied a valued option and if so, what its value was.
lookupArgument :: LongName -> Parameters -> Maybe String Source #
Arguments are mandatory, so by the time your program is running a value has already been identified. This returns the value for that parameter.
lookupEnvironmentValue :: LongName -> Parameters -> Maybe String Source #
Look to see if the user supplied the named environment variable and if so, return what its value was.
getProgramName :: Program τ Rope Source #
Get the program name as invoked from the command-line (or as overridden by
setProgramName
).
setProgramName :: Rope -> Program τ () Source #
Override the program name used for logging, etc. At least, that was the
idea. Nothing makes use of this at the moment. :/
setVerbosityLevel :: Verbosity -> Program τ () Source #
getConsoleWidth :: Program τ Int Source #
Retreive the current terminal's width, in characters.
If you are outputting an object with a Render
instance then you may not need this; you can instead use wrteR
which is
aware of the width of your terminal and will reflow (in as much as the
underlying type's Render
instance lets it).
getApplicationState :: Program τ τ Source #
Get the user supplied application state as originally supplied to
configure
and modified subsequntly by replacement with
setApplicationState
.
state <- getApplicationState
setApplicationState :: τ -> Program τ () Source #
Update the user supplied top-level application state.
let state' = state { answer = 42 } setApplicationState state'
Useful actions
outputEntire :: Handle -> Bytes -> Program τ () Source #
Write the supplied Bytes
to the given Handle
. Note that in contrast to
write
we don't output a trailing newline.
output
h b
Do not use this to output to stdout
as that would bypass the mechanism
used by the write
*, event
, and debug
* functions to sequence output
correctly. If you wish to write to the terminal use:
write
(intoRope
b)
(which is not unsafe, but will lead to unexpected results if the binary blob you pass in is other than UTF-8 text).
inputEntire :: Handle -> Program τ Bytes Source #
Read the (entire) contents of the specified Handle
.
execProcess :: [Rope] -> Program τ (ExitCode, Rope, Rope) Source #
Execute an external child process and wait for its output and result. The command is specified first and and subsequent arguments as elements of the list. This helper then logs the command being executed to the debug output, which can be useful when you're trying to find out what exactly what program is being invoked.
Keep in mind that this isn't invoking a shell; arguments and their values have to be enumerated separately:
execProcess
["/usr/bin/ssh", "-l", "admin", "203.0.113.42", "\'remote command here\'"]
having to write out the individual options and arguments and deal with escaping is a bit of an annoyance but that's execvp(3) for you.
The return tuple is the exit code from the child process, its entire stdout
and its entire stderr
, if any. Note that this is not a streaming interface,
so if you're doing something that returns huge amounts of output you'll want
to use something like io-streams instead.
(this wraps typed-process's readProcess
)
Concurrency
A thread for concurrent computation. Haskell uses green threads: small lines of work that are scheduled down onto actual execution contexts, set by default by this library to be one per core. They are incredibly lightweight, and you are encouraged to use them freely. Haskell provides a rich ecosystem of tools to do work concurrently and to communicate safely between threads
(this wraps async's Async
)
forkThread :: Program τ α -> Program τ (Thread α) Source #
Fork a thread. The child thread will run in the same Context
as the calling
Program
, including sharing the user-defined application state type.
(this wraps async's async
which in turn wraps base's
forkIO
)
sleepThread :: Rational -> Program τ () Source #
Pause the current thread for the given number of seconds. For example, to delay a second and a half, do:
sleepThread
1.5
(this wraps base's threadDelay
)
resetTimer :: Program τ () Source #
Reset the start time (used to calculate durations shown in event- and
debug-level logging) held in the Context
to zero. This is useful if you want
to see the elapsed time taken by a specific worker rather than seeing log
entries relative to the program start time which is the default.
If you want to start time held on your main program thread to maintain a count of the total elapsed program time, then fork a new thread for your worker and reset the timer there.
forkThread
$ doresetTimer
...
then times output in the log messages will be relative to that call to
resetTimer
, not the program start.
waitThread :: Thread α -> Program τ α Source #
Wait for the completion of a thread, returning the result. This is a blocking operation.
(this wraps async's wait
)
waitThread_ :: Thread α -> Program τ () Source #
Wait for the completion of a thread, discarding its result. This is particularly useful at the end of a do-block if you're waiting on a worker thread to finish but don't need its return value, if any; otherwise you have to explicily deal with the unused return value:
_ <-waitThread
t1return
()
which is a bit tedious. Instead, you can just use this convenience function:
waitThread_
t1
The trailing underscore in the name of this function follows the same
convetion as found in Control.Monad, which has mapM_
which
does the same as mapM
but which likewise discards the return
value.
trap_ :: Program τ α -> Program τ () Source #
Trap any exceptions coming out of the given Program action, and discard them. The one and only time you want this is inside an endless loop:
forever $ do trap_ ( bracket obtainResource releaseResource useResource )
This function really will swollow expcetions, which means that you'd better
have handled any synchronous checked errors already with a catch
and/or have
released resources with bracket
or finally
as shown above.
An info level message will be sent to the log channel indicating that an uncaught exception was trapped along with a debug level message showing the exception text, if any.
Internals
Internal context for a running program. You access this via actions in the
Program
monad. The principal item here is the user-supplied top-level
application data of type τ
which can be retrieved with
getApplicationState
and updated with
setApplicationState
.
A Program
with no user-supplied state to be threaded throughout the
computation.
The Core.Program.Execute framework makes your top-level application state available at the outer level of your process. While this is a feature that most substantial programs rely on, it is not needed for many simple tasks or when first starting out what will become a larger project.
This is effectively the unit type, but this alias is here to clearly signal a user-data type is not a part of the program semantics.
invalid :: Program τ α Source #
Illegal internal state resulting from what should be unreachable code or otherwise a programmer error.
A utility exception for those occasions when you just need to go "boom".
Instances
Show Boom Source # | |
Exception Boom Source # | |
Defined in Core.Program.Context toException :: Boom -> SomeException # fromException :: SomeException -> Maybe Boom # displayException :: Boom -> String # |