]> gitweb.michael.orlitzky.com - hath.git/blobdiff - src/Main.hs
Add a CommandLine module for parsing command-line options.
[hath.git] / src / Main.hs
index c87520951088c46f095f334bd90e78587b98c53d..3dfa546e374c84b6c86cd2bdce848285d5fd2ea8 100644 (file)
@@ -1,5 +1,7 @@
 import Data.List (intercalate, intersperse)
-import System.Exit (exitFailure)
+import System.Exit (ExitCode(..), exitWith)
+import System.IO (stderr, hPutStrLn)
+
 import Text.Regex.Posix
 
 import Cidr (Cidr,
@@ -13,6 +15,18 @@ import Cidr (Cidr,
              max_third_octet,
              max_fourth_octet)
 
+import CommandLine (help_set,
+                    help_text,
+                    input_function,
+                    parse_errors)
+
+-- Some exit codes, used in the ExitFailure constructor.
+exit_invalid_cidr :: Int
+exit_invalid_cidr = 1
+
+exit_args_parse_failed :: Int
+exit_args_parse_failed = 2
+
 
 -- A regular expression that matches a non-address character.
 non_addr_char :: String
@@ -76,7 +90,7 @@ numeric_range x y =
        upper = maximum [x,y]
 
 
--- Take a CIDR String, and exitFailure if it's invalid.
+-- Take a CIDR String, and exit with a failure if it's invalid.
 validate_or_die :: String -> IO ()
 validate_or_die cidr = do
   if (is_valid_cidr cidr)
@@ -84,15 +98,36 @@ validate_or_die cidr = do
       return ()
     else do
         putStrLn "Error: not valid CIDR notation."
-        exitFailure
+        exitWith (ExitFailure exit_invalid_cidr)
+
 
 
 main :: IO ()
 main = do
-  input <- getContents
+  -- First, check for any errors that occurred while parsing
+  -- the command line options.
+  errors <- CommandLine.parse_errors
+  if not (null errors)
+    then do
+      hPutStrLn stderr (concat errors)
+      putStrLn CommandLine.help_text
+      exitWith (ExitFailure exit_args_parse_failed)
+    else do -- Nothing
+
+  -- Next, check to see if the 'help' option was passed to the
+  -- program. If it was, display the help, and exit successfully.
+  help_opt_set <- CommandLine.help_set
+  if help_opt_set
+    then do
+      putStrLn CommandLine.help_text
+      exitWith ExitSuccess
+    else do -- Nothing
+
+  -- The input function we receive here should know what to read.
+  inputfunc <- (CommandLine.input_function)
+  input <- inputfunc
   let cidr_strings = lines input
   mapM validate_or_die cidr_strings
   let cidrs = map Cidr.from_string cidr_strings
   let regexes = map cidr_to_regex cidrs
   putStrLn $ alternate regexes
-