1"""
2This module provides aggregated private data and utilities functions about the
3available backends.
4
5WARNING: The *pathspec._backends* package is not part of the public API. Its
6contents and structure are likely to change.
7"""
8
9from collections.abc import (
10 Sequence)
11from typing import (
12 cast)
13
14from ..pattern import (
15 Pattern,
16 RegexPattern)
17
18from .base import (
19 Backend,
20 BackendNamesHint)
21from .hyperscan.base import (
22 hyperscan_error)
23from .hyperscan.gitignore import (
24 HyperscanGiBackend)
25from .hyperscan.pathspec import (
26 HyperscanPsBackend)
27from .re2.base import (
28 re2_error)
29from .re2.gitignore import (
30 Re2GiBackend)
31from .re2.pathspec import (
32 Re2PsBackend)
33from .simple.gitignore import (
34 SimpleGiBackend)
35from .simple.pathspec import (
36 SimplePsBackend)
37
38_BEST_BACKEND: BackendNamesHint
39"""
40The best available backend.
41"""
42
43if hyperscan_error is None:
44 _BEST_BACKEND = 'hyperscan'
45elif re2_error is None:
46 _BEST_BACKEND = 're2'
47else:
48 _BEST_BACKEND = 'simple'
49
50
51def make_gitignore_backend(
52 name: BackendNamesHint,
53 patterns: Sequence[Pattern],
54) -> Backend:
55 """
56 Create the specified backend with the supplied patterns for
57 :class:`~pathspec.gitignore.GitIgnoreSpec`.
58
59 *name* (:class:`str`) is the name of the backend.
60
61 *patterns* (:class:`.Iterable` of :class:`.Pattern`) contains the compiled
62 patterns.
63
64 Returns the backend (:class:`.Backend`).
65 """
66 if name == 'best':
67 name = _BEST_BACKEND
68
69 if name == 're2':
70 return Re2GiBackend(cast(Sequence[RegexPattern], patterns))
71 elif name == 'hyperscan':
72 return HyperscanGiBackend(cast(Sequence[RegexPattern], patterns))
73 elif name == 'simple':
74 return SimpleGiBackend(cast(Sequence[RegexPattern], patterns))
75 else:
76 raise ValueError(f"Backend {name=!r} is invalid.")
77
78
79def make_pathspec_backend(
80 name: BackendNamesHint,
81 patterns: Sequence[Pattern],
82) -> Backend:
83 """
84 Create the specified backend with the supplied patterns for
85 :class:`~pathspec.pathspec.PathSpec`.
86
87 *name* (:class:`str`) is the name of the backend.
88
89 *patterns* (:class:`Iterable` of :class:`Pattern`) contains the compiled
90 patterns.
91
92 Returns the backend (:class:`.Backend`).
93 """
94 if name == 'best':
95 name = _BEST_BACKEND
96
97 if name == 're2':
98 return Re2PsBackend(cast(Sequence[RegexPattern], patterns))
99 elif name == 'hyperscan':
100 return HyperscanPsBackend(cast(Sequence[RegexPattern], patterns))
101 elif name == 'simple':
102 return SimplePsBackend(patterns)
103 else:
104 raise ValueError(f"Backend {name=!r} is invalid.")