From 5c93d48d440cb00d2a25cc57b5a1b642197f27cd Mon Sep 17 00:00:00 2001 From: Alice BRENON <alice.brenon@ens-lyon.fr> Date: Fri, 12 Feb 2021 18:13:13 +0100 Subject: [PATCH] Handle errors in Main a bit more cleanly than with 'error', shutting down cleanly with the error message and no stack trace --- app/Main.hs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/app/Main.hs b/app/Main.hs index 5f4032e..6c8fa8a 100644 --- a/app/Main.hs +++ b/app/Main.hs @@ -9,21 +9,22 @@ import qualified Data.Text.IO as Text (getContents, readFile, writeFile) import Text.InvisiXML (InvisiXML(..), parse) import Text.XML.Light.Serializer (encode) import System.FilePath ((<.>), dropExtension) +import System.Exit (die) -endPoints :: Command -> (IO Text, FilePath) +endPoints :: Command -> IO (IO Text, FilePath) endPoints (Command {input = StdIn, outputPrefix}) = - (Text.getContents, fromMaybe noOutputPrefix outputPrefix) + (,) Text.getContents <$> maybe noOutputPrefix return outputPrefix where - noOutputPrefix = error "output prefix (-o) is necessary when running on stdin" + noOutputPrefix = die "output prefix (-o) is necessary when running on stdin" endPoints (Command {input = FileInput f, outputPrefix}) = - (Text.readFile f, fromMaybe (dropExtension f) outputPrefix) + return (Text.readFile f, fromMaybe (dropExtension f) outputPrefix) run :: Command -> IO () -run command = - source >>= runExceptT . parse >>= either (fail . show) create +run command = do + (source, prefix) <- endPoints command + source >>= runExceptT . parse >>= either (fail . show) (create prefix) where - (source, prefix) = endPoints command - create (InvisiXML {text, structure}) = do + create prefix (InvisiXML {text, structure}) = do Text.writeFile (prefix <.> "txt") text writeFile (prefix <.> "ixml") $ encode structure -- GitLab