1--
2-- Copyright (c) 2013-2019 Nicola Bonelli <nicola@pfq.io>
3--
4-- This program is free software; you can redistribute it and/or modify
5-- it under the terms of the GNU General Public License as published by
6-- the Free Software Foundation; either version 2 of the License, or
7-- (at your option) any later version.
8--
9-- This program is distributed in the hope that it will be useful,
10-- but WITHOUT ANY WARRANTY; without even the implied warranty of
11-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12-- GNU General Public License for more details.
13--
14-- You should have received a copy of the GNU General Public License
15-- along with this program; if not, write to the Free Software
16-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17--
18
19module CGrep.Common ( Text8
20                    , getTargetName
21                    , getTargetContents
22                    , shallowSearch
23                    , runSearch
24                    , expandMultiline
25                    , ignoreCase
26                    , trim
27                    , trim8
28                    , takeN) where
29
30import qualified Data.ByteString.Char8 as C
31import qualified Data.ByteString.Search as SC
32
33import Data.Char
34
35import CGrep.Types
36import CGrep.Output
37
38import Options
39import Reader
40import Util
41
42
43takeN :: Int -> String -> String
44takeN n xs | length xs > n = take n xs ++ "..."
45          | otherwise     = xs
46
47
48trim :: String -> String
49trim = (dropWhile isSpace . reverse) . dropWhile isSpace . reverse
50
51
52trim8 :: Text8 -> Text8
53trim8 = (C.dropWhile isSpace . C.reverse) . C.dropWhile isSpace . C.reverse
54
55
56getTargetName :: FilePath -> String
57getTargetName [] = "<STDIN>"
58getTargetName name = name
59
60
61getTargetContents :: FilePath -> IO Text8
62getTargetContents [] = C.getContents
63getTargetContents xs = C.readFile xs
64
65
66shallowSearch :: [Text8] -> Text8 -> [[Int]]
67shallowSearch ps text = ps >>= (\p -> [p `SC.nonOverlappingIndices` text])
68
69
70runSearch :: Options
71          -> FilePath
72          -> Bool
73          -> OptionT IO [Output]
74          -> OptionT IO [Output]
75runSearch opt filename shallowTest doSearch =
76    if shallowTest || no_shallow opt
77        then doSearch
78        else mkOutput filename C.empty C.empty []
79
80
81expandMultiline :: Options -> Text8 -> Text8
82expandMultiline Options { multiline = n } xs
83    | n == 1 = xs
84    | otherwise = C.unlines $ map C.unwords $ spanGroup n (C.lines xs)
85
86
87ignoreCase :: Options -> Text8 -> Text8
88ignoreCase opt
89    | ignore_case opt =  C.map toLowercase
90    | otherwise = id
91