-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmbox-grep.hs
82 lines (73 loc) · 3.04 KB
/
mbox-grep.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
77
78
79
80
81
{-# LANGUAGE TemplateHaskell, TypeOperators #-}
--------------------------------------------------------------------
-- |
-- Executable : mbox-grep
-- Copyright : (c) Nicolas Pouillard 2008, 2009, 2010, 2011
-- License : BSD3
--
-- Maintainer: Nicolas Pouillard <[email protected]>
-- Stability : provisional
-- Portability:
--
--------------------------------------------------------------------
import Codec.Mbox (Mbox(..), MboxMessage(..), Direction(..), parseMboxFiles, opposite)
import Email (Email(..),ShowFormat(..),fmtOpt,defaultShowFormat,
readEmail,putEmails,showFormatsDoc,stringOfField)
import System.Environment (getArgs)
import Text.ParserCombinators.Parsec (parse)
import Hutt.Query (evalQueryMsg,parseQuery)
import Hutt.Types(Msg(..),Dsc(..),MsgId(..),DscId(..),Query(..))
import Data.Tree (Tree(..))
import Control.Arrow
import System.Console.GetOpt
data Settings = Settings { _fmt :: ShowFormat
, _dir :: Direction
, _help :: Bool
}
$(makeLenses ''Settings)
type Flag = Settings -> Settings
grepMbox :: Settings -> String -> [String] -> IO ()
grepMbox opts queryString = (mapM_ f =<<) . parseMboxFiles (opts^.dir)
where query = either (error "malformed query") id $ parse parseQuery "<first-argument>" queryString
f = putEmails (opts^.fmt)
. filter (emailMatchQuery query . fst)
. map ((readEmail . view mboxMsgBody) &&& id) . mboxMessages
emailMatchQuery :: Query -> Email -> Bool
emailMatchQuery query email = evalQueryMsg (msg, dsc) query
where msg = Msg { msgHeader = map stringOfField $ emailFields email
--, msgBody = rawEmail email
, msgContent = rawEmail email -- emailContent email
, msgId = MsgId 0
, msgLabels = []
, msgAddress = undefined
, msgParent = Nothing
, msgReferences = [] }
dsc = Dsc { dscId = DscId 0
, dscMsgs = Node () []
, dscLabels = [] }
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
(queryString : files, []) -> grepMbox opts queryString files
(_, []) -> usage "Too few arguments"
_ -> usage (concat errs)
defaultSettings :: Settings
defaultSettings = Settings { _fmt = defaultShowFormat
, _dir = Forward
, _help = False
}
usage :: String -> a
usage msg = error $ unlines [msg, usageInfo header options, showFormatsDoc]
where header = "Usage: mbox-grep [OPTIONS] <query> <mbox-file>*"
options :: [OptDescr Flag]
options =
[ fmtOpt usage (set fmt)
, Option "r" ["reverse"] (NoArg (modify dir opposite)) "Reverse the mbox order (latest firsts)"
, Option "?" ["help"] (NoArg (set help True)) "Show this help message"
]