-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflags.hs
57 lines (50 loc) · 1.93 KB
/
flags.hs
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
-- | Simple module for handling command line flags, where each flag starts
-- | with an arbitrary number of hyphens, followed by a word, and optionally an
-- | equals sign and an argument.
-- | Example: -a, --add, --file=myfile.txt
module Flags(
parseFlags,
isSet,
getFlagArg,
getFlagArgSafe,
maybeFlags
)
where
import Data.Map as Map (Map, fromList, lookup)
import Data.Maybe
-- | A flag, such as -f or --no-edit
type Flag = String
type FlagArg = String
type FlagList = Map Flag (Maybe FlagArg)
-- | Takes a list of command line arguments and converts them to a dictionery of
-- | flags and their values.
parseFlags :: [String] -> FlagList
parseFlags = fromList . map (\flag -> (parseFlag flag, if getFlagArg flag == []
then Nothing
else Just (getFlagArg flag)
)
) .
Prelude.filter isFlag
where
isFlag ('-':rest) = True
isFlag _ = False
parseFlag = takeWhile (/='=') . dropWhile (=='-')
getFlagArg = drop 1 . dropWhile (/='=')
-- | Checks wether a flag exists in a given flag dictionary.
isSet :: Flag -> FlagList -> Bool
isSet f fs
| isNothing (Map.lookup f fs) = False
| otherwise = True
-- | Get argument for first occurence of given flag.
getFlagArgSafe :: Flag -> FlagList -> Maybe FlagArg
getFlagArgSafe f fs | isSet f fs = fromJust $ Map.lookup f fs
| otherwise = Nothing
-- | Get the argument for a flag. Will crash if the flag doesn't exist.
getFlagArg :: Flag -> FlagList -> FlagArg
getFlagArg f fs = fromJust $ getFlagArgSafe f fs
-- | If the requested flag exists, returns its argument, otherwise the
-- | fallback value.
maybeFlags :: FlagArg -> Flag -> FlagList -> FlagArg
maybeFlags fallback flag flags = if isSet flag flags
then getFlagArg flag flags
else fallback