ghcup-hs/lib/GHCup/Utils/Bash.hs

70 lines
2.2 KiB
Haskell
Raw Normal View History

2020-03-03 00:59:19 +00:00
module GHCup.Utils.Bash
2020-01-16 22:27:38 +00:00
( findAssignment
, equalsAssignmentWith
, getRValue
, getAssignmentValueFor
)
where
2020-01-14 21:55:34 +00:00
2020-01-16 22:27:38 +00:00
import Control.Monad
2020-03-01 00:05:02 +00:00
import Data.ByteString.UTF8 ( toString )
import Data.List
2020-01-16 22:27:38 +00:00
import Data.Maybe
2020-03-01 00:05:02 +00:00
import HPath
import HPath.IO
import Language.Bash.Parse
import Language.Bash.Syntax
import Language.Bash.Word
2020-01-16 22:27:38 +00:00
import Prelude hiding ( readFile )
2020-03-01 00:05:02 +00:00
import qualified Data.ByteString.Lazy.UTF8 as UTF8
2020-01-14 21:55:34 +00:00
2020-01-16 22:27:38 +00:00
extractAssignments :: List -> [Assign]
extractAssignments (List stms) = join $ fmap getAssign $ getCommands stms
where
getCommands :: [Statement] -> [Command]
getCommands = join . fmap commands . catMaybes . fmap findPipes
where
findPipes (Statement (Last p@(Pipeline{})) Sequential) = Just p
findPipes _ = Nothing
2020-01-14 21:55:34 +00:00
2020-01-16 22:27:38 +00:00
getAssign :: Command -> [Assign]
getAssign (Command (SimpleCommand ass _) _) = ass
getAssign _ = []
2020-01-14 21:55:34 +00:00
-- | Find an assignment matching the predicate in the given file.
2020-01-16 22:27:38 +00:00
findAssignment :: Path b -> (Assign -> Bool) -> IO (Maybe Assign)
2020-01-14 21:55:34 +00:00
findAssignment p predicate = do
2020-01-16 22:27:38 +00:00
fileContents <- readFile p
-- TODO: this should accept bytestring:
-- https://github.com/knrafto/language-bash/issues/37
case parse (toString . toFilePath $ p) (UTF8.toString fileContents) of
Left e -> fail $ show e
Right l -> pure $ find predicate (extractAssignments $ l)
2020-01-14 21:55:34 +00:00
-- | Check that the assignment is of the form Foo= ignoring the
-- right hand-side.
equalsAssignmentWith :: String -> Assign -> Bool
equalsAssignmentWith n ass = case ass of
(Assign (Parameter name' Nothing) Equals _) -> n == name'
_ -> False
-- | This pretty-prints the right hand of an Equals assignment, removing
-- quotations. No evaluation is performed.
getRValue :: Assign -> Maybe String
getRValue ass = case ass of
(Assign (Parameter _ _) Equals (RValue w)) -> Just $ unquote w
_ -> Nothing
-- | Given a bash assignment such as Foo="Bar" in the given file,
-- will return "Bar" (without quotations).
getAssignmentValueFor :: Path b -> String -> IO (Maybe String)
getAssignmentValueFor p n = do
mass <- findAssignment p (equalsAssignmentWith n)
pure (mass >>= getRValue)