Skip to content

Instantly share code, notes, and snippets.

@rightfold
Forked from ThomasLocke/passgen.hs
Last active Aug 29, 2015
Embed
What would you like to do?
A Haskell noob trying to create sorta-kinda random passwords
import Control.Applicative
import System.Environment
import System.Exit
import System.Random
main = getArgs >>= parseArgs
-- Exit with success.
exit :: IO a
exit = exitWith ExitSuccess
-- Generate an x long password. The initial s String is appended to the
-- password.
generatePassword :: Int -> IO String -> IO String
generatePassword x s
| x < 1 = s
| otherwise = generatePassword (x -1) (liftA2 (:) randChar s)
-- Print the help text.
help :: String
help = "Usage: passgen OPTION\n" ++
" -l x outputs a random password of x length\n" ++
" -h this help text\n" ++
" -v version of the program"
-- Parse the commandline arguments and return one of:
-- help
-- version
-- actual program output
parseArgs :: [String] -> IO ()
parseArgs ("-l":n:[]) = generatePassword (read n :: Int) (return "") >>= putStrLn >> exit
parseArgs [] = putStrLn help >> exit
parseArgs ["-h"] = putStrLn help >> exit
parseArgs ["--help"] = putStrLn help >> exit
parseArgs ["-v"] = putStrLn version >> exit
parseArgs ["--version"] = putStrLn version >> exit
parseArgs (a:as) = putStrLn help >> exit
-- Yields a random char from the validChars list.
randChar :: IO Char
randChar = randNum >>= (\i -> return (validChars !! i))
-- Yields a random integer in the 0 .. length validChars range.
randNum :: IO Int
randNum = getStdRandom (randomR (0, (length validChars) - 1))
-- A list of valid characters
validChars :: String
validChars = ['a'..'z'] ++ ['0'..'9'] ++ ['A'..'Z']
-- Print the version
version :: String
version = "0.0.1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment