summaryrefslogtreecommitdiff
path: root/Utility/Glob.hs
blob: d35a968493aa7003635302bd4c4c8e4a447f5995 (plain)
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
{- file globbing
 -
 - This uses TDFA when available, with a fallback to regex-compat.
 - TDFA is less buggy in its support for non-unicode characters.
 -
 - Copyright 2014 Joey Hess <id@joeyh.name>
 -
 - License: BSD-2-clause
 -}

{-# LANGUAGE CPP #-}

module Utility.Glob (
	Glob,
	GlobCase(..),
	compileGlob,
	matchGlob
) where

import System.Path.WildMatch

#ifdef WITH_TDFA
import Text.Regex.TDFA
import Text.Regex.TDFA.String
#else
import Text.Regex
import Data.Maybe
#endif

newtype Glob = Glob Regex

data GlobCase = CaseSensative | CaseInsensative

{- Compiles a glob to a regex, that can be repeatedly used. -}
compileGlob :: String -> GlobCase -> Glob
compileGlob glob globcase = Glob $
#ifdef WITH_TDFA
	case compile (defaultCompOpt {caseSensitive = casesentitive}) defaultExecOpt regex of
		Right r -> r
		Left _ -> error $ "failed to compile regex: " ++ regex
#else
	mkRegexWithOpts regex casesentitive True
#endif
  where
	regex = '^':wildToRegex glob
	casesentitive = case globcase of
		CaseSensative -> True
		CaseInsensative -> False

matchGlob :: Glob -> String -> Bool
matchGlob (Glob regex) val = 
#ifdef WITH_TDFA
	case execute regex val of
		Right (Just _) -> True
		_ -> False
#else
	isJust $ matchRegex regex val
#endif