Refactor main

This commit is contained in:
Rnhmjoj 2014-10-14 19:14:44 +02:00
parent 8a40514984
commit 99cc0a1093
2 changed files with 21 additions and 22 deletions

View File

@ -1,5 +1,5 @@
name: alea
version: 0.1.0.0
version: 0.1.1.0
synopsis: a diceware passphrase generator
description:

39
main.hs
View File

@ -2,13 +2,11 @@
import System.IO
import System.Console.CmdArgs
import System.Environment (getArgs, withArgs)
import Control.Monad (when)
import Paths_alea (getDataFileName)
import Diceware
import Random
import Alea.Diceware
import Alea.Random
_NAME = "Alea"
_VERSION = "0.1.0"
@ -41,25 +39,26 @@ getProgArgs = cmdArgs $ progArgs
main :: IO ()
main = do
args <- getArgs
opts <- getProgArgs
exec opts
main = getProgArgs >>= defaults >>= exec
-- Assign defaults value to unspecified args
defaults :: Args -> IO Args
defaults args@Args{..} = do
dictionary <- getDataFileName "dict/diceware" >>= readFile
return args
{ dictionary = dictionary
, phraseLength = if phraseLength == 0 then 6 else phraseLength
}
exec :: Args -> IO ()
exec opts@Args{..} = do
opts <- getProgArgs
defaultDict <- getDataFileName "diceware"
file <- readFile (if null dictionary then defaultDict else dictionary)
exec args@Args{..} =
if interactive
then interact (unlines . map (dice file) . lines)
then interact (unlines . map dice . lines)
else do
phrase <- randWords (size $ parseDiceware file) phraseLength'
putStrLn . unwords . map (dice' file) $ phrase
when (phrases > 1) $ exec opts {phrases = phrases - 1}
randWords dictSize phraseLength >>= putStrLn . unwords . map dice'
when (phrases > 1) $ exec args {phrases = phrases - 1}
where
-- helpers
dice x n = readDiceware (parseDiceware x) (read n :: Int)
dice' x n = readDiceware' (parseDiceware x) n
-- default arguments
phraseLength' = if phraseLength == 0 then 6 else phraseLength
dice n = readDiceware (parseDiceware dictionary) (read n :: Int)
dice' n = readDiceware' (parseDiceware dictionary) n
dictSize = size $ parseDiceware dictionary