-
Notifications
You must be signed in to change notification settings - Fork 0
/
mbox-pick.hs
77 lines (66 loc) · 2.51 KB
/
mbox-pick.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
{-# LANGUAGE TemplateHaskell, TypeOperators #-}
--------------------------------------------------------------------
-- |
-- Executable : mbox-pick
-- Copyright : (c) Nicolas Pouillard 2008, 2009, 2011
-- License : BSD3
--
-- Maintainer: Nicolas Pouillard <[email protected]>
-- Stability : provisional
-- Portability:
--
--------------------------------------------------------------------
import Control.Arrow
import Control.Lens
import Control.Applicative
import Data.Maybe (fromMaybe, listToMaybe)
import qualified Data.ByteString.Lazy.Char8 as C
import Codec.Mbox (mboxMsgBody,parseOneMboxMessage)
import Email (readEmail)
import EmailFmt (putEmails,ShowFormat(..),fmtOpt,defaultShowFormat,showFormatsDoc)
import System.Environment (getArgs)
import System.Console.GetOpt
import System.IO (IOMode(..), stdin, openFile, hClose)
mayRead :: Read a => String -> Maybe a
mayRead s = case reads s of
[(x, "")] -> Just x
_ -> Nothing
parseSeq :: C.ByteString -> Maybe [Integer]
parseSeq = mapM (mayRead . C.unpack) . C.split ','
data Settings = Settings { _fmt :: ShowFormat
, _help :: Bool
}
$(makeLenses ''Settings)
type Flag = Settings -> Settings
pickMbox :: Settings -> String -> Maybe FilePath -> IO ()
pickMbox opts sequ' mmbox = do
mbox <- maybe (return stdin) (`openFile` ReadMode) mmbox
sequ <- maybe (fail "badly formatted comma separated offset sequence") return $ parseSeq $ C.pack sequ'
mails <- mapM ((((readEmail . view mboxMsgBody) &&& id) <$>) . parseOneMboxMessage (fromMaybe "" mmbox) mbox) sequ
putEmails (opts^.fmt) mails
hClose mbox
defaultSettings :: Settings
defaultSettings = Settings { _fmt = defaultShowFormat
, _help = False
}
usage :: String -> a
usage msg = error $ unlines [msg, usageInfo header options, showFormatsDoc]
where header = "Usage: mbox-pick [OPTION] <offset0>,<offset1>,...,<offsetN> <mbox-file>"
options :: [OptDescr Flag]
options =
[ fmtOpt usage (set fmt)
, Option "?" ["help"] (NoArg (set help True)) "Show this help message"
]
main :: IO ()
main = do
args <- getArgs
let (flags, nonopts, errs) = getOpt Permute options args
let opts = foldr ($) defaultSettings flags
if opts^.help
then usage ""
else
case (nonopts, errs) of
([], []) -> usage "Too few arguments"
(_:_:_:_, []) -> usage "Too many arguments"
(sequ : mbox, []) -> pickMbox opts sequ $ listToMaybe mbox
(_, _) -> usage (concat errs)