Implement a tiny cat version
We only support a single file which gets written to stdout. Non-existing files or other errors are printed to stderr and the program terminates.
This commit is contained in:
parent
babdc90cef
commit
81b0437bb7
2 changed files with 28 additions and 2 deletions
|
|
@ -3,4 +3,4 @@ module Main (main) where
|
||||||
import HCat qualified
|
import HCat qualified
|
||||||
|
|
||||||
main :: IO ()
|
main :: IO ()
|
||||||
main = HCat.runHCat
|
main = HCat.defaultMain
|
||||||
|
|
|
||||||
28
src/HCat.hs
28
src/HCat.hs
|
|
@ -1,6 +1,32 @@
|
||||||
module HCat (
|
module HCat (
|
||||||
runHCat,
|
runHCat,
|
||||||
|
defaultMain,
|
||||||
) where
|
) where
|
||||||
|
|
||||||
|
import System.Environment qualified as Env
|
||||||
|
import System.IO (hPutStrLn, stderr)
|
||||||
|
|
||||||
|
import Control.Exception qualified as Exception
|
||||||
|
import System.IO.Error qualified as IOError
|
||||||
|
|
||||||
|
parseArgs :: [String] -> Either String FilePath
|
||||||
|
parseArgs args = case args of
|
||||||
|
[] -> Left "No filename given!"
|
||||||
|
[arg] -> Right arg
|
||||||
|
_ -> Left "Only a single file is supported"
|
||||||
|
|
||||||
runHCat :: IO ()
|
runHCat :: IO ()
|
||||||
runHCat = pure ()
|
runHCat = do
|
||||||
|
fileNameOrError <- parseArgs <$> Env.getArgs
|
||||||
|
fileName <- eitherToError fileNameOrError
|
||||||
|
readFile fileName >>= putStr
|
||||||
|
|
||||||
|
eitherToError :: Show a => Either a b -> IO b
|
||||||
|
eitherToError = either (Exception.throwIO . IOError.userError . show) return
|
||||||
|
|
||||||
|
handleError :: IOError -> IO ()
|
||||||
|
handleError e = do
|
||||||
|
hPutStrLn stderr $ "I ran into an issue: " <> show e
|
||||||
|
|
||||||
|
defaultMain :: IO ()
|
||||||
|
defaultMain = Exception.catch runHCat handleError
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue