Skip to content

Commit

Permalink
Write to stdout when no output file is specified
Browse files Browse the repository at this point in the history
  • Loading branch information
sol committed Jul 10, 2023
1 parent 64c7a5b commit ed2a6b1
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
20 changes: 16 additions & 4 deletions src/Text/Markdown/Unlit.hs
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,27 @@ run args =
--
case break (== "-h") args of
(xs, ["-h", fileName, infile, outfile]) ->
fmap (unlit fileName $ mkSelector xs) (readFileUtf8 infile) >>= writeFileUtf8 outfile
readFileUtf8 infile >>= writeFileUtf8 outfile . unlit fileName (mkSelector xs)

(xs, ["-h", infile]) ->
readFileUtf8 infile >>= writeUtf8 stdout . unlit infile (mkSelector xs)

_ -> do
name <- getProgName
hPutStrLn stderr ("usage: " ++ name ++ " [selector] -h label infile outfile")
hPutStrLn stderr ("usage: " ++ name ++ " [selector] -h SRC CUR DST")
exitFailure
where
mkSelector :: [String] -> Selector
mkSelector = fromMaybe ("haskell" :&: Not "ignore") . parseSelector . unwords
readFileUtf8 name = openFile name ReadMode >>= \h -> hSetEncoding h utf8 >> hGetContents h
writeFileUtf8 name str = withFile name WriteMode (\h -> hSetEncoding h utf8 >> hPutStr h str)

readFileUtf8 :: FilePath -> IO String
readFileUtf8 name = openFile name ReadMode >>= \ handle -> hSetEncoding handle utf8 >> hGetContents handle

writeFileUtf8 :: FilePath -> String -> IO ()
writeFileUtf8 name str = withFile name WriteMode $ \ handle -> writeUtf8 handle str

writeUtf8 :: Handle -> String -> IO ()
writeUtf8 handle str = hSetEncoding handle utf8 >> hPutStr handle str

unlit :: FilePath -> Selector -> String -> String
unlit fileName selector = unlines . concatMap formatCB . filter (toP selector . codeBlockClasses) . parse
Expand Down
2 changes: 1 addition & 1 deletion test/Text/Markdown/UnlitSpec.hs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ spec = do
it "prints a usage message" $ do
withProgName "foo" $ do
(r, Left (ExitFailure 1)) <- hCapture [stderr] (try $ run [])
r `shouldBe` "usage: foo [selector] -h label infile outfile\n"
r `shouldBe` "usage: foo [selector] -h SRC CUR DST\n"

it "unlits code marked with .haskell by default (unless it is marked with .ignore as well)" $ do
withTempFile $ \infile -> withTempFile $ \outfile -> do
Expand Down

0 comments on commit ed2a6b1

Please sign in to comment.