7 import Control.Monad (mplus)
9 import Data.Maybe (isJust)
10 import Data.Monoid (Monoid(..))
11 import System.Directory (
12 getAppUserDataDirectory
14 import System.Exit (ExitCode(..), exitWith)
15 import System.FilePath.Posix (joinPath)
16 import System.IO (hPutStrLn, stderr)
18 import qualified CommandLine as Cmd (
25 -- | Contains all of our configurable options.
29 password :: Maybe String,
30 username :: Maybe String }
33 instance Monoid Cfg where
34 mempty = Cfg { article = "",
40 let article' = (if null article1 then article2 else article1)
41 output' = (if null output1 then output2 else output1)
42 password' = password1 `mplus` password2
43 username' = username1 `mplus` username2
45 Cfg { article = article',
48 username = username' }
54 password1 = password c1
55 password2 = password c2
56 username1 = username c1
57 username2 = username c2
60 use_account :: Cfg -> Bool
62 (isJust $ username cfg) && (isJust $ password cfg)
64 format_cpe :: CPError -> String
65 format_cpe (ParseError desc, _) = "Parse error: " ++ desc
66 format_cpe (SectionAlreadyExists desc, _) = "Section already exists: " ++ desc
67 format_cpe (NoSection desc, _) = "Missing section: " ++ desc
68 format_cpe (NoOption desc, _) = "Missing required option: " ++ desc
69 format_cpe (OtherProblem desc, _) = "Error: " ++ desc
70 format_cpe (InterpolationError desc, _) = "Interpolation error: " ++ desc
73 -- | The config parsing functions return either the result or a
74 -- 'CPError'. If there was an error, we represent it as 'Nothing'
75 -- (at least if we're forcing the value into a 'Maybe'
76 -- wrapper. Otherwise, we return 'Just' the result.
77 either_to_maybe :: Either CPError a -> Maybe a
78 either_to_maybe (Left _) = Nothing
79 either_to_maybe (Right x) = Just x
82 config_filename :: String
83 config_filename = Cmd.program_name ++ ".conf"
85 config_path :: IO FilePath
87 cfg_dir <- getAppUserDataDirectory Cmd.program_name
88 return $ joinPath [cfg_dir, config_filename]
90 parse_config :: IO (Either String Cfg)
92 cfg_file <- config_path
93 parse_result <- readfile emptyCP cfg_file
97 Left err -> Left (format_cpe err)
99 let cp_username = get cp "DEFAULT" "username"
100 cp_password = get cp "DEFAULT" "password"
102 cfg_username = either_to_maybe cp_username
103 cfg_password = either_to_maybe cp_password
105 Right $ mempty { username = cfg_username,
106 password = cfg_password }
112 cmd_article <- Cmd.apply_args
113 let arg_cfg = mempty { article = Cmd.article cmd_article,
114 output = Cmd.output cmd_article }
116 either_file_cfg <- parse_config
117 case either_file_cfg of
120 exitWith $ ExitFailure exit_config_parse_failed
122 -- The left operand takes precedence when both are non-empty!
123 return $ arg_cfg `mappend` file_cfg