about summary refs log tree commit diff
path: root/users/Profpatsch/arglib/ArglibNetencode.hs
blob: e4609d26abf56468ae4892003c136c8cb3b2d738 (plain) (blame)
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
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}

module ArglibNetencode where

import qualified Data.Attoparsec.ByteString as Atto
import Data.Maybe (fromMaybe)
import ExecHelpers
import MyPrelude
import Netencode
import qualified System.Environment as Env
import qualified System.Posix.Env.ByteString as ByteEnv

arglibNetencode :: CurrentProgramName -> Maybe Text -> IO T
arglibNetencode progName mEnvvar = do
  let envvar = mEnvvar & fromMaybe "ARGLIB_NETENCODE" & textToBytesUtf8
  ByteEnv.getEnv envvar >>= \case
    Nothing -> dieUserError progName [fmt|could not read args, envvar {envvar} not set|]
    Just bytes ->
      case Atto.parseOnly (Netencode.netencodeParser <* Atto.endOfInput) bytes of
        Left err -> dieEnvironmentProblem progName [fmt|arglib parsing error: {err}|]
        Right t -> do
          ByteEnv.unsetEnv envvar
          pure t