matra-lint 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- matra_lint-0.1.0/.github/workflows/ci.yml +20 -0
- matra_lint-0.1.0/.github/workflows/publish.yml +42 -0
- matra_lint-0.1.0/.gitignore +6 -0
- matra_lint-0.1.0/LICENSE +21 -0
- matra_lint-0.1.0/PKG-INFO +112 -0
- matra_lint-0.1.0/README.md +89 -0
- matra_lint-0.1.0/action.yml +32 -0
- matra_lint-0.1.0/pyproject.toml +36 -0
- matra_lint-0.1.0/src/matra/__init__.py +8 -0
- matra_lint-0.1.0/src/matra/cli.py +158 -0
- matra_lint-0.1.0/src/matra/corpus.py +25 -0
- matra_lint-0.1.0/src/matra/fuzz.py +101 -0
- matra_lint-0.1.0/src/matra/rules.py +166 -0
- matra_lint-0.1.0/src/matra/scanner.py +121 -0
- matra_lint-0.1.0/tests/test_fuzz.py +53 -0
- matra_lint-0.1.0/tests/test_rules.py +122 -0
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
name: ci
|
|
2
|
+
on:
|
|
3
|
+
push:
|
|
4
|
+
pull_request:
|
|
5
|
+
jobs:
|
|
6
|
+
test:
|
|
7
|
+
runs-on: ubuntu-24.04
|
|
8
|
+
strategy:
|
|
9
|
+
matrix:
|
|
10
|
+
python: ["3.10", "3.12", "3.13"]
|
|
11
|
+
steps:
|
|
12
|
+
- uses: actions/checkout@v4
|
|
13
|
+
- uses: actions/setup-python@v5
|
|
14
|
+
with:
|
|
15
|
+
python-version: ${{ matrix.python }}
|
|
16
|
+
- run: pip install -e '.[test]'
|
|
17
|
+
- run: pytest -q
|
|
18
|
+
- run: matra demo
|
|
19
|
+
# Matra scans itself: its own code must be clean at medium confidence.
|
|
20
|
+
- run: matra check src --min-confidence medium
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# Publishes to PyPI when a version tag (v0.1.0, ...) is pushed.
|
|
2
|
+
# Uses PyPI Trusted Publishing (OIDC), so no API token is stored anywhere.
|
|
3
|
+
# One-time setup on pypi.org: Account > Publishing > add a pending publisher with
|
|
4
|
+
# project: matra-lint owner: RaktimChandra repo: matra-lint
|
|
5
|
+
# workflow: publish.yml environment: pypi
|
|
6
|
+
name: publish
|
|
7
|
+
on:
|
|
8
|
+
push:
|
|
9
|
+
tags: ["v*"]
|
|
10
|
+
workflow_dispatch:
|
|
11
|
+
|
|
12
|
+
jobs:
|
|
13
|
+
build:
|
|
14
|
+
runs-on: ubuntu-24.04
|
|
15
|
+
steps:
|
|
16
|
+
- uses: actions/checkout@v4
|
|
17
|
+
- uses: actions/setup-python@v5
|
|
18
|
+
with:
|
|
19
|
+
python-version: "3.12"
|
|
20
|
+
- run: pip install -e '.[test]' build twine
|
|
21
|
+
- run: pytest -q
|
|
22
|
+
- run: python -m build
|
|
23
|
+
- run: twine check dist/*
|
|
24
|
+
- uses: actions/upload-artifact@v4
|
|
25
|
+
with:
|
|
26
|
+
name: dist
|
|
27
|
+
path: dist/
|
|
28
|
+
|
|
29
|
+
pypi:
|
|
30
|
+
needs: build
|
|
31
|
+
runs-on: ubuntu-24.04
|
|
32
|
+
environment:
|
|
33
|
+
name: pypi
|
|
34
|
+
url: https://pypi.org/p/matra-lint
|
|
35
|
+
permissions:
|
|
36
|
+
id-token: write
|
|
37
|
+
steps:
|
|
38
|
+
- uses: actions/download-artifact@v4
|
|
39
|
+
with:
|
|
40
|
+
name: dist
|
|
41
|
+
path: dist/
|
|
42
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
matra_lint-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Raktim Chandra
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: matra-lint
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Find code that breaks text written in Indian scripts: shattered words, rejected names, split syllables.
|
|
5
|
+
Project-URL: Homepage, https://github.com/RaktimChandra/matra-lint
|
|
6
|
+
Author-email: Raktim Chandra <raktimchandra26@gmail.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: bengali,devanagari,grapheme,hindi,i18n,indic,linter,sarif,tamil,unicode
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Natural Language :: Bengali
|
|
13
|
+
Classifier: Natural Language :: Hindi
|
|
14
|
+
Classifier: Natural Language :: Tamil
|
|
15
|
+
Classifier: Natural Language :: Telugu
|
|
16
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
17
|
+
Classifier: Topic :: Text Processing :: Linguistic
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Requires-Dist: regex>=2023.0
|
|
20
|
+
Provides-Extra: test
|
|
21
|
+
Requires-Dist: pytest>=8; extra == 'test'
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# matra
|
|
25
|
+
|
|
26
|
+
**Find code that breaks text written in Indian scripts.**
|
|
27
|
+
|
|
28
|
+
Most text code is written and tested in English. Run it on Hindi, Bengali, Tamil or any of India's scripts and it fails quietly: words fall apart, real names are rejected, and truncated text ends in half a syllable. The cause is almost always the same. Indian scripts write vowels as **combining marks** (matras) attached to consonants, and ASCII-minded code does not count those marks as letters.
|
|
29
|
+
|
|
30
|
+
`matra` finds that code in JavaScript/TypeScript, Python, Go and Rust, shows the word it breaks, and gives the fix. `matra fuzz` then proves it by running your own functions on real words in 11 scripts.
|
|
31
|
+
|
|
32
|
+
```
|
|
33
|
+
$ matra demo
|
|
34
|
+
What ASCII-minded Python does to Indian-script text:
|
|
35
|
+
|
|
36
|
+
re.findall(r'\w+', 'हिंदी') -> ['ह', 'द']
|
|
37
|
+
'हिंदी'.isalpha() -> False
|
|
38
|
+
re.fullmatch(r'[A-Za-z ]+', 'प्रिया') -> None
|
|
39
|
+
'क्षमा'[:2] -> 'क्'
|
|
40
|
+
'हिंदी'[::-1] -> 'ीदंिह'
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
None of these is exotic. `'हिंदी'.isalpha()` is `False`, and so is `isalpha()` for every word with a vowel sign in Tamil, Bengali, Telugu, Punjabi and the rest. So a name check built on it rejects every name written in an Indian script. In JavaScript, `/\w+/u` matches nothing at all in `'हिंदी'`, and `\b` finds no word boundary in `'தமிழ்'`.
|
|
44
|
+
|
|
45
|
+
## Install
|
|
46
|
+
|
|
47
|
+
```
|
|
48
|
+
pip install git+https://github.com/RaktimChandra/matra-lint
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Use
|
|
52
|
+
|
|
53
|
+
```
|
|
54
|
+
matra check . # scan a project
|
|
55
|
+
matra check src --min-confidence medium
|
|
56
|
+
matra check . --format sarif > matra.sarif # GitHub code scanning
|
|
57
|
+
matra rules # every rule with its evidence
|
|
58
|
+
matra fuzz myapp.text:truncate --kind truncate
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
`check` exits with 1 when it finds something, so it can gate CI. Silence a line with `# matra: ignore` or `// matra: ignore[MAT006]`, or a whole file (fixtures, test data) with `matra: ignore-file` in its first 10 lines.
|
|
62
|
+
|
|
63
|
+
## Rules
|
|
64
|
+
|
|
65
|
+
Every rule's evidence is checked by the test suite against the real runtime, not assumed.
|
|
66
|
+
|
|
67
|
+
| Rule | Languages | Confidence | Flags | Breaks because |
|
|
68
|
+
| --- | --- | --- | --- | --- |
|
|
69
|
+
| MAT001 ascii-word-class | JS/TS, Python, Go | medium | `\w`, `\b` in a regex | `re.findall(r'\w+', 'हिंदी') == ['ह', 'द']`; in JS `/\w+/u` finds nothing |
|
|
70
|
+
| MAT002 letters-without-marks | all | high | `[\p{L}...]+` with no `\p{M}` | `'हिंदी'.match(/[\p{L}]+/gu)` gives `['ह', 'द']` |
|
|
71
|
+
| MAT003 isalpha-rejects-indic | Python | high | `.isalpha()`, `.isalnum()` | `False` for every word with a vowel sign |
|
|
72
|
+
| MAT004 go-isletter-without-ismark | Go | medium | `unicode.IsLetter` with no `IsMark` in the file | vowel signs are category M, not L |
|
|
73
|
+
| MAT005 ascii-only-name-pattern | all | medium | `[A-Za-z]` on a name, city or address | rejects `प्रिया` |
|
|
74
|
+
| MAT006 truncation-splits-syllables | all | low | `title.slice(0, n)`, `text[:n]`, `&name[..n]` | `'क्षमा'[:2] == 'क्'`; in Rust a byte cut can panic |
|
|
75
|
+
| MAT007 per-character-reversal | all | low | `s[::-1]`, `.split('').reverse()` | `'हिंदी'[::-1]` starts with an orphan vowel sign |
|
|
76
|
+
|
|
77
|
+
Rust's `\w` already includes marks, so MAT001 skips Rust.
|
|
78
|
+
|
|
79
|
+
## Fuzz your own functions
|
|
80
|
+
|
|
81
|
+
Static rules can only guess. The fuzz checks run your function on real words and report exactly which word broke:
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
from matra.fuzz import check_truncate, check_tokenize, check_validator
|
|
85
|
+
|
|
86
|
+
check_truncate(my_truncate) # my_truncate(text, n) -> str: must end on a grapheme boundary
|
|
87
|
+
check_tokenize(my_tokenize) # my_tokenize(text) -> list[str]: must keep words whole
|
|
88
|
+
check_validator(is_valid_name) # is_valid_name(name) -> bool: must accept real names
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Grapheme boundaries come from Unicode's own rules (UAX #29, including the conjunct rules added in Unicode 15.1), via the `regex` module.
|
|
92
|
+
|
|
93
|
+
## In CI
|
|
94
|
+
|
|
95
|
+
```yaml
|
|
96
|
+
- uses: RaktimChandra/matra-lint@main
|
|
97
|
+
with:
|
|
98
|
+
min-confidence: medium # findings also appear in the Security tab
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## Found in the wild
|
|
102
|
+
|
|
103
|
+
- A hotel-booking app's `validate_name` used `^[A-Za-z]+...$`. `matra fuzz --kind validate` showed it rejected all 9 real names in 9 scripts (राकेश, முருகன், সৌরভ, ...).
|
|
104
|
+
- [Clipy #982](https://github.com/clipy-recorder/clipy/issues/982): a transcript grouper used `char::is_alphanumeric`, which counts vowel signs as letters, so a lone `ि` token after a pause split `कि` into two segments.
|
|
105
|
+
|
|
106
|
+
## Limits
|
|
107
|
+
|
|
108
|
+
This is a line-based scanner, not a type checker. It cannot know whether a given `title[:40]` ever sees Indian-script text, which is why truncation and reversal are marked low confidence. Use `--min-confidence medium` for a quieter first run.
|
|
109
|
+
|
|
110
|
+
## License
|
|
111
|
+
|
|
112
|
+
MIT
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# matra
|
|
2
|
+
|
|
3
|
+
**Find code that breaks text written in Indian scripts.**
|
|
4
|
+
|
|
5
|
+
Most text code is written and tested in English. Run it on Hindi, Bengali, Tamil or any of India's scripts and it fails quietly: words fall apart, real names are rejected, and truncated text ends in half a syllable. The cause is almost always the same. Indian scripts write vowels as **combining marks** (matras) attached to consonants, and ASCII-minded code does not count those marks as letters.
|
|
6
|
+
|
|
7
|
+
`matra` finds that code in JavaScript/TypeScript, Python, Go and Rust, shows the word it breaks, and gives the fix. `matra fuzz` then proves it by running your own functions on real words in 11 scripts.
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
$ matra demo
|
|
11
|
+
What ASCII-minded Python does to Indian-script text:
|
|
12
|
+
|
|
13
|
+
re.findall(r'\w+', 'हिंदी') -> ['ह', 'द']
|
|
14
|
+
'हिंदी'.isalpha() -> False
|
|
15
|
+
re.fullmatch(r'[A-Za-z ]+', 'प्रिया') -> None
|
|
16
|
+
'क्षमा'[:2] -> 'क्'
|
|
17
|
+
'हिंदी'[::-1] -> 'ीदंिह'
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
None of these is exotic. `'हिंदी'.isalpha()` is `False`, and so is `isalpha()` for every word with a vowel sign in Tamil, Bengali, Telugu, Punjabi and the rest. So a name check built on it rejects every name written in an Indian script. In JavaScript, `/\w+/u` matches nothing at all in `'हिंदी'`, and `\b` finds no word boundary in `'தமிழ்'`.
|
|
21
|
+
|
|
22
|
+
## Install
|
|
23
|
+
|
|
24
|
+
```
|
|
25
|
+
pip install git+https://github.com/RaktimChandra/matra-lint
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Use
|
|
29
|
+
|
|
30
|
+
```
|
|
31
|
+
matra check . # scan a project
|
|
32
|
+
matra check src --min-confidence medium
|
|
33
|
+
matra check . --format sarif > matra.sarif # GitHub code scanning
|
|
34
|
+
matra rules # every rule with its evidence
|
|
35
|
+
matra fuzz myapp.text:truncate --kind truncate
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
`check` exits with 1 when it finds something, so it can gate CI. Silence a line with `# matra: ignore` or `// matra: ignore[MAT006]`, or a whole file (fixtures, test data) with `matra: ignore-file` in its first 10 lines.
|
|
39
|
+
|
|
40
|
+
## Rules
|
|
41
|
+
|
|
42
|
+
Every rule's evidence is checked by the test suite against the real runtime, not assumed.
|
|
43
|
+
|
|
44
|
+
| Rule | Languages | Confidence | Flags | Breaks because |
|
|
45
|
+
| --- | --- | --- | --- | --- |
|
|
46
|
+
| MAT001 ascii-word-class | JS/TS, Python, Go | medium | `\w`, `\b` in a regex | `re.findall(r'\w+', 'हिंदी') == ['ह', 'द']`; in JS `/\w+/u` finds nothing |
|
|
47
|
+
| MAT002 letters-without-marks | all | high | `[\p{L}...]+` with no `\p{M}` | `'हिंदी'.match(/[\p{L}]+/gu)` gives `['ह', 'द']` |
|
|
48
|
+
| MAT003 isalpha-rejects-indic | Python | high | `.isalpha()`, `.isalnum()` | `False` for every word with a vowel sign |
|
|
49
|
+
| MAT004 go-isletter-without-ismark | Go | medium | `unicode.IsLetter` with no `IsMark` in the file | vowel signs are category M, not L |
|
|
50
|
+
| MAT005 ascii-only-name-pattern | all | medium | `[A-Za-z]` on a name, city or address | rejects `प्रिया` |
|
|
51
|
+
| MAT006 truncation-splits-syllables | all | low | `title.slice(0, n)`, `text[:n]`, `&name[..n]` | `'क्षमा'[:2] == 'क्'`; in Rust a byte cut can panic |
|
|
52
|
+
| MAT007 per-character-reversal | all | low | `s[::-1]`, `.split('').reverse()` | `'हिंदी'[::-1]` starts with an orphan vowel sign |
|
|
53
|
+
|
|
54
|
+
Rust's `\w` already includes marks, so MAT001 skips Rust.
|
|
55
|
+
|
|
56
|
+
## Fuzz your own functions
|
|
57
|
+
|
|
58
|
+
Static rules can only guess. The fuzz checks run your function on real words and report exactly which word broke:
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
from matra.fuzz import check_truncate, check_tokenize, check_validator
|
|
62
|
+
|
|
63
|
+
check_truncate(my_truncate) # my_truncate(text, n) -> str: must end on a grapheme boundary
|
|
64
|
+
check_tokenize(my_tokenize) # my_tokenize(text) -> list[str]: must keep words whole
|
|
65
|
+
check_validator(is_valid_name) # is_valid_name(name) -> bool: must accept real names
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Grapheme boundaries come from Unicode's own rules (UAX #29, including the conjunct rules added in Unicode 15.1), via the `regex` module.
|
|
69
|
+
|
|
70
|
+
## In CI
|
|
71
|
+
|
|
72
|
+
```yaml
|
|
73
|
+
- uses: RaktimChandra/matra-lint@main
|
|
74
|
+
with:
|
|
75
|
+
min-confidence: medium # findings also appear in the Security tab
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Found in the wild
|
|
79
|
+
|
|
80
|
+
- A hotel-booking app's `validate_name` used `^[A-Za-z]+...$`. `matra fuzz --kind validate` showed it rejected all 9 real names in 9 scripts (राकेश, முருகன், সৌরভ, ...).
|
|
81
|
+
- [Clipy #982](https://github.com/clipy-recorder/clipy/issues/982): a transcript grouper used `char::is_alphanumeric`, which counts vowel signs as letters, so a lone `ि` token after a pause split `कि` into two segments.
|
|
82
|
+
|
|
83
|
+
## Limits
|
|
84
|
+
|
|
85
|
+
This is a line-based scanner, not a type checker. It cannot know whether a given `title[:40]` ever sees Indian-script text, which is why truncation and reversal are marked low confidence. Use `--min-confidence medium` for a quieter first run.
|
|
86
|
+
|
|
87
|
+
## License
|
|
88
|
+
|
|
89
|
+
MIT
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
name: matra
|
|
2
|
+
description: Find code that breaks text written in Indian scripts, and report it in GitHub code scanning.
|
|
3
|
+
branding:
|
|
4
|
+
icon: type
|
|
5
|
+
color: orange
|
|
6
|
+
inputs:
|
|
7
|
+
path:
|
|
8
|
+
description: Directory to scan.
|
|
9
|
+
default: "."
|
|
10
|
+
min-confidence:
|
|
11
|
+
description: low, medium or high.
|
|
12
|
+
default: medium
|
|
13
|
+
upload-sarif:
|
|
14
|
+
description: Upload results to GitHub code scanning (needs security-events write).
|
|
15
|
+
default: "true"
|
|
16
|
+
runs:
|
|
17
|
+
using: composite
|
|
18
|
+
steps:
|
|
19
|
+
- uses: actions/setup-python@v5
|
|
20
|
+
with:
|
|
21
|
+
python-version: "3.12"
|
|
22
|
+
- shell: bash
|
|
23
|
+
run: pip install "${{ github.action_path }}"
|
|
24
|
+
- shell: bash
|
|
25
|
+
run: matra check "${{ inputs.path }}" --min-confidence "${{ inputs.min-confidence }}" --format sarif --exit-zero > matra.sarif
|
|
26
|
+
- if: inputs.upload-sarif == 'true'
|
|
27
|
+
uses: github/codeql-action/upload-sarif@v3
|
|
28
|
+
with:
|
|
29
|
+
sarif_file: matra.sarif
|
|
30
|
+
category: matra
|
|
31
|
+
- shell: bash
|
|
32
|
+
run: matra check "${{ inputs.path }}" --min-confidence "${{ inputs.min-confidence }}"
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "matra-lint"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Find code that breaks text written in Indian scripts: shattered words, rejected names, split syllables."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
authors = [{ name = "Raktim Chandra", email = "raktimchandra26@gmail.com" }]
|
|
13
|
+
keywords = ["unicode", "indic", "hindi", "i18n", "linter", "devanagari", "tamil", "bengali", "grapheme", "sarif"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 3 - Alpha",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"Topic :: Software Development :: Quality Assurance",
|
|
18
|
+
"Topic :: Text Processing :: Linguistic",
|
|
19
|
+
"Natural Language :: Hindi",
|
|
20
|
+
"Natural Language :: Bengali",
|
|
21
|
+
"Natural Language :: Tamil",
|
|
22
|
+
"Natural Language :: Telugu",
|
|
23
|
+
]
|
|
24
|
+
dependencies = ["regex>=2023.0"]
|
|
25
|
+
|
|
26
|
+
[project.optional-dependencies]
|
|
27
|
+
test = ["pytest>=8"]
|
|
28
|
+
|
|
29
|
+
[project.scripts]
|
|
30
|
+
matra = "matra.cli:main"
|
|
31
|
+
|
|
32
|
+
[project.urls]
|
|
33
|
+
Homepage = "https://github.com/RaktimChandra/matra-lint"
|
|
34
|
+
|
|
35
|
+
[tool.hatch.build.targets.wheel]
|
|
36
|
+
packages = ["src/matra"]
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""matra: find code that breaks text written in Indian scripts.
|
|
2
|
+
|
|
3
|
+
matra check [PATH ...] [--format text|json|sarif] [--select MAT003,...]
|
|
4
|
+
[--ignore ...] [--min-confidence low|medium|high] [--exit-zero]
|
|
5
|
+
matra rules
|
|
6
|
+
matra demo # see the failures happen, live, in this Python
|
|
7
|
+
matra fuzz MODULE:FUNCTION --kind truncate|tokenize|validate
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import importlib
|
|
14
|
+
import json
|
|
15
|
+
import re
|
|
16
|
+
import sys
|
|
17
|
+
from collections import Counter
|
|
18
|
+
|
|
19
|
+
from . import __version__
|
|
20
|
+
from .rules import BY_ID, RULES
|
|
21
|
+
from .scanner import scan
|
|
22
|
+
|
|
23
|
+
RULES_URL = "https://github.com/RaktimChandra/matra-lint#rules"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _csv(value: str | None) -> set[str]:
|
|
27
|
+
return {v.strip().upper() for v in (value or "").split(",") if v.strip()}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _sarif(findings) -> dict:
|
|
31
|
+
used = sorted({f.rule.id for f in findings})
|
|
32
|
+
level = {"high": "error", "medium": "warning", "low": "note"}
|
|
33
|
+
return {
|
|
34
|
+
"$schema": "https://json.schemastore.org/sarif-2.1.0.json",
|
|
35
|
+
"version": "2.1.0",
|
|
36
|
+
"runs": [{
|
|
37
|
+
"tool": {"driver": {
|
|
38
|
+
"name": "matra", "version": __version__, "informationUri": RULES_URL,
|
|
39
|
+
"rules": [{
|
|
40
|
+
"id": BY_ID[i].id, "name": BY_ID[i].name,
|
|
41
|
+
"shortDescription": {"text": BY_ID[i].message},
|
|
42
|
+
"fullDescription": {"text": f"{BY_ID[i].message} Evidence: {BY_ID[i].evidence}"},
|
|
43
|
+
"help": {"text": " ".join(f"{k}: {v}" for k, v in BY_ID[i].fix.items())},
|
|
44
|
+
"defaultConfiguration": {"level": level[BY_ID[i].confidence]},
|
|
45
|
+
} for i in used],
|
|
46
|
+
}},
|
|
47
|
+
"results": [{
|
|
48
|
+
"ruleId": f.rule.id,
|
|
49
|
+
"level": level[f.rule.confidence],
|
|
50
|
+
"message": {"text": f"{f.rule.message} Fix: {f.fix}"},
|
|
51
|
+
"locations": [{"physicalLocation": {
|
|
52
|
+
"artifactLocation": {"uri": f.path.replace("\\", "/").lstrip("./")},
|
|
53
|
+
"region": {"startLine": f.line, "startColumn": f.column},
|
|
54
|
+
}}],
|
|
55
|
+
} for f in findings],
|
|
56
|
+
}],
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def cmd_check(args) -> int:
|
|
61
|
+
findings = scan(args.paths or ["."], _csv(args.select), _csv(args.ignore), args.min_confidence)
|
|
62
|
+
if args.format == "json":
|
|
63
|
+
print(json.dumps([{
|
|
64
|
+
"rule": f.rule.id, "name": f.rule.name, "confidence": f.rule.confidence,
|
|
65
|
+
"path": f.path, "line": f.line, "column": f.column, "code": f.snippet,
|
|
66
|
+
"message": f.rule.message, "evidence": f.rule.evidence, "fix": f.fix,
|
|
67
|
+
} for f in findings], ensure_ascii=False, indent=2))
|
|
68
|
+
elif args.format == "sarif":
|
|
69
|
+
print(json.dumps(_sarif(findings), ensure_ascii=False, indent=2))
|
|
70
|
+
else:
|
|
71
|
+
for f in findings:
|
|
72
|
+
print(f"{f.path}:{f.line}:{f.column}: {f.rule.id} [{f.rule.confidence}] {f.rule.message}")
|
|
73
|
+
print(f" {f.snippet}")
|
|
74
|
+
print(f" fix: {f.fix}")
|
|
75
|
+
counts = Counter(f.rule.id for f in findings)
|
|
76
|
+
summary = ", ".join(f"{k} x{v}" for k, v in sorted(counts.items())) or "none"
|
|
77
|
+
print(f"\n{len(findings)} finding(s): {summary}", file=sys.stderr)
|
|
78
|
+
return 0 if args.exit_zero or not findings else 1
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def cmd_rules(_args) -> int:
|
|
82
|
+
for r in RULES:
|
|
83
|
+
print(f"{r.id} {r.name} [{r.confidence}] ({', '.join(sorted(r.languages))})")
|
|
84
|
+
print(f" {r.message}")
|
|
85
|
+
print(f" evidence: {r.evidence}\n")
|
|
86
|
+
return 0
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def cmd_demo(_args) -> int:
|
|
90
|
+
word, name = "हिंदी", "प्रिया"
|
|
91
|
+
rows = [
|
|
92
|
+
("re.findall(r'\\w+', 'हिंदी')", re.findall(r"\w+", word)), # matra: ignore
|
|
93
|
+
("'हिंदी'.isalpha()", word.isalpha()), # matra: ignore
|
|
94
|
+
("re.fullmatch(r'[A-Za-z ]+', 'प्रिया')", re.fullmatch(r"[A-Za-z ]+", name)), # matra: ignore
|
|
95
|
+
("'क्षमा'[:2]", "क्षमा"[:2]),
|
|
96
|
+
("'हिंदी'[::-1]", word[::-1]),
|
|
97
|
+
]
|
|
98
|
+
print("What ASCII-minded Python does to Indian-script text:\n")
|
|
99
|
+
for expr, got in rows:
|
|
100
|
+
print(f" {expr:<42} -> {got!r}")
|
|
101
|
+
try:
|
|
102
|
+
import regex
|
|
103
|
+
print("\nWith grapheme- and mark-aware code (the `regex` module):\n")
|
|
104
|
+
fixed = [
|
|
105
|
+
(r"regex.findall(r'[\p{L}\p{M}\p{N}_]+', 'हिंदी')", regex.findall(r"[\p{L}\p{M}\p{N}_]+", word)),
|
|
106
|
+
(r"regex.findall(r'\X', 'क्षमा')[:1]", regex.findall(r"\X", "क्षमा")[:1]),
|
|
107
|
+
]
|
|
108
|
+
for expr, got in fixed:
|
|
109
|
+
print(f" {expr:<42} -> {got!r}")
|
|
110
|
+
except ImportError:
|
|
111
|
+
pass
|
|
112
|
+
return 0
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def cmd_fuzz(args) -> int:
|
|
116
|
+
from . import fuzz
|
|
117
|
+
module_name, _, attr = args.target.partition(":")
|
|
118
|
+
if not attr:
|
|
119
|
+
print("target must be MODULE:FUNCTION", file=sys.stderr)
|
|
120
|
+
return 2
|
|
121
|
+
sys.path.insert(0, ".")
|
|
122
|
+
fn = getattr(importlib.import_module(module_name), attr)
|
|
123
|
+
check = {"truncate": fuzz.check_truncate, "tokenize": fuzz.check_tokenize, "validate": fuzz.check_validator}[args.kind]
|
|
124
|
+
problems = check(fn)
|
|
125
|
+
for p in problems:
|
|
126
|
+
print(p)
|
|
127
|
+
print(f"\n{len(problems)} problem(s) in {args.target} ({args.kind})", file=sys.stderr)
|
|
128
|
+
return 1 if problems else 0
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def main(argv: list[str] | None = None) -> int:
|
|
132
|
+
parser = argparse.ArgumentParser(prog="matra", description="Find code that breaks text written in Indian scripts.")
|
|
133
|
+
parser.add_argument("--version", action="version", version=f"matra {__version__}")
|
|
134
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
135
|
+
|
|
136
|
+
p = sub.add_parser("check", help="scan source files")
|
|
137
|
+
p.add_argument("paths", nargs="*")
|
|
138
|
+
p.add_argument("--format", choices=["text", "json", "sarif"], default="text")
|
|
139
|
+
p.add_argument("--select", help="only these rule ids, comma separated")
|
|
140
|
+
p.add_argument("--ignore", help="skip these rule ids, comma separated")
|
|
141
|
+
p.add_argument("--min-confidence", choices=["low", "medium", "high"], default="low")
|
|
142
|
+
p.add_argument("--exit-zero", action="store_true", help="exit 0 even with findings")
|
|
143
|
+
p.set_defaults(func=cmd_check)
|
|
144
|
+
|
|
145
|
+
sub.add_parser("rules", help="list the rules with their evidence").set_defaults(func=cmd_rules)
|
|
146
|
+
sub.add_parser("demo", help="show the failures live").set_defaults(func=cmd_demo)
|
|
147
|
+
|
|
148
|
+
p = sub.add_parser("fuzz", help="run your function on real Indian-script words")
|
|
149
|
+
p.add_argument("target", help="MODULE:FUNCTION")
|
|
150
|
+
p.add_argument("--kind", choices=["truncate", "tokenize", "validate"], required=True)
|
|
151
|
+
p.set_defaults(func=cmd_fuzz)
|
|
152
|
+
|
|
153
|
+
args = parser.parse_args(argv)
|
|
154
|
+
return args.func(args)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
if __name__ == "__main__":
|
|
158
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Real words that trip text-handling code, one list per script.
|
|
2
|
+
|
|
3
|
+
Every word carries at least one combining mark (a vowel sign, virama, nukta
|
|
4
|
+
or anusvara): the code points that ASCII-minded code treats as "not a letter".
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
WORDS: dict[str, list[str]] = {
|
|
8
|
+
"Devanagari (Hindi)": ["हिंदी", "किताब", "क्षमा", "प्रेम", "शुक्रिया"],
|
|
9
|
+
"Devanagari (Marathi)": ["मराठी", "महाराष्ट्र"],
|
|
10
|
+
"Bengali": ["বাংলা", "ভালোবাসা", "কলকাতা"],
|
|
11
|
+
"Tamil": ["தமிழ்", "நன்றி", "சென்னை"],
|
|
12
|
+
"Telugu": ["తెలుగు", "హైదరాబాద్"],
|
|
13
|
+
"Kannada": ["ಕನ್ನಡ", "ಬೆಂಗಳೂರು"],
|
|
14
|
+
"Malayalam": ["മലയാളം", "കേരളം"],
|
|
15
|
+
"Gujarati": ["ગુજરાતી", "અમદાવાદ"],
|
|
16
|
+
"Gurmukhi (Punjabi)": ["ਪੰਜਾਬੀ", "ਅੰਮ੍ਰਿਤਸਰ"],
|
|
17
|
+
"Odia": ["ଓଡ଼ିଆ", "ଭୁବନେଶ୍ୱର"],
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
#: Personal names, for checks on validation code.
|
|
21
|
+
NAMES: list[str] = ["राकेश", "प्रिया", "সৌরভ", "முருகன்", "శ్రీనివాస్", "ಅನಿಲ್", "ഗീത", "ગીતા", "ਹਰਪ੍ਰੀਤ"]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def all_words() -> list[str]:
|
|
25
|
+
return [w for words in WORDS.values() for w in words] + NAMES
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Run your own text functions on real Indian-script words and report where
|
|
2
|
+
they break a syllable. Static rules guess; these prove.
|
|
3
|
+
|
|
4
|
+
from matra.fuzz import check_truncate, check_tokenize, check_validator
|
|
5
|
+
|
|
6
|
+
problems = check_truncate(my_truncate) # my_truncate(text, n) -> str
|
|
7
|
+
problems = check_tokenize(my_tokenize) # my_tokenize(text) -> list[str]
|
|
8
|
+
problems = check_validator(is_valid_name) # is_valid_name(text) -> bool
|
|
9
|
+
|
|
10
|
+
Each returns a list of `Problem`; an empty list means every corpus word passed.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import unicodedata
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from typing import Callable, Iterable
|
|
18
|
+
|
|
19
|
+
import regex
|
|
20
|
+
|
|
21
|
+
from .corpus import NAMES, all_words
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class Problem:
|
|
26
|
+
check: str
|
|
27
|
+
input: str
|
|
28
|
+
output: object
|
|
29
|
+
why: str
|
|
30
|
+
|
|
31
|
+
def __str__(self) -> str:
|
|
32
|
+
return f"{self.check}: {self.input!r} -> {self.output!r}: {self.why}"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def graphemes(text: str) -> list[str]:
|
|
36
|
+
"""Extended grapheme clusters (Unicode UAX #29, with the Indic conjunct rules)."""
|
|
37
|
+
return regex.findall(r"\X", text)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _boundaries(text: str) -> set[int]:
|
|
41
|
+
out, at = {0}, 0
|
|
42
|
+
for g in graphemes(text):
|
|
43
|
+
at += len(g)
|
|
44
|
+
out.add(at)
|
|
45
|
+
return out
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _starts_with_mark(s: str) -> bool:
|
|
49
|
+
return bool(s) and unicodedata.category(s[0]).startswith("M")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def check_truncate(fn: Callable[[str, int], str], words: Iterable[str] | None = None,
|
|
53
|
+
max_len: int = 12) -> list[Problem]:
|
|
54
|
+
"""`fn(text, n)` should return a prefix of `text` that ends on a grapheme boundary."""
|
|
55
|
+
problems = []
|
|
56
|
+
for word in words or all_words():
|
|
57
|
+
bounds = _boundaries(word)
|
|
58
|
+
for n in range(1, min(max_len, len(word)) + 1):
|
|
59
|
+
try:
|
|
60
|
+
out = fn(word, n)
|
|
61
|
+
except Exception as e: # noqa: BLE001 - a crash is a finding
|
|
62
|
+
problems.append(Problem("truncate", word, f"{type(e).__name__}: {e}", f"raised at n={n}"))
|
|
63
|
+
break
|
|
64
|
+
if not isinstance(out, str) or not word.startswith(out):
|
|
65
|
+
problems.append(Problem("truncate", word, out, f"not a prefix of the input (n={n})"))
|
|
66
|
+
break
|
|
67
|
+
if len(out) not in bounds:
|
|
68
|
+
problems.append(Problem("truncate", word, out, f"cuts through a syllable (n={n})"))
|
|
69
|
+
break
|
|
70
|
+
return problems
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def check_tokenize(fn: Callable[[str], list[str]], words: Iterable[str] | None = None) -> list[Problem]:
|
|
74
|
+
"""`fn(text)` should keep each word whole and never start a token with a vowel sign."""
|
|
75
|
+
problems = []
|
|
76
|
+
for word in words or all_words():
|
|
77
|
+
sentence = f"{word} {word}"
|
|
78
|
+
try:
|
|
79
|
+
tokens = list(fn(sentence))
|
|
80
|
+
except Exception as e: # noqa: BLE001
|
|
81
|
+
problems.append(Problem("tokenize", sentence, f"{type(e).__name__}: {e}", "raised"))
|
|
82
|
+
continue
|
|
83
|
+
if any(_starts_with_mark(t) for t in tokens):
|
|
84
|
+
problems.append(Problem("tokenize", sentence, tokens, "a token starts with a vowel sign"))
|
|
85
|
+
elif word not in tokens:
|
|
86
|
+
problems.append(Problem("tokenize", sentence, tokens, "the word was not kept whole"))
|
|
87
|
+
return problems
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def check_validator(fn: Callable[[str], bool], names: Iterable[str] | None = None) -> list[Problem]:
|
|
91
|
+
"""`fn(name)` should accept real names written in Indian scripts."""
|
|
92
|
+
problems = []
|
|
93
|
+
for name in names or NAMES:
|
|
94
|
+
try:
|
|
95
|
+
ok = fn(name)
|
|
96
|
+
except Exception as e: # noqa: BLE001
|
|
97
|
+
problems.append(Problem("validate", name, f"{type(e).__name__}: {e}", "raised"))
|
|
98
|
+
continue
|
|
99
|
+
if not ok:
|
|
100
|
+
problems.append(Problem("validate", name, ok, "a real name was rejected"))
|
|
101
|
+
return problems
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""matra: ignore-file (this file holds the bad patterns as examples)
|
|
2
|
+
|
|
3
|
+
The rules. Each one is a pattern of code that breaks text written in Indian
|
|
4
|
+
scripts, with the evidence that it does (measured, not assumed) and the fix.
|
|
5
|
+
|
|
6
|
+
Languages: js (JavaScript and TypeScript), py, go, rs.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class Rule:
|
|
17
|
+
id: str
|
|
18
|
+
name: str
|
|
19
|
+
languages: frozenset[str]
|
|
20
|
+
pattern: re.Pattern[str]
|
|
21
|
+
confidence: str # "high" | "medium" | "low"
|
|
22
|
+
message: str
|
|
23
|
+
evidence: str
|
|
24
|
+
fix: dict[str, str]
|
|
25
|
+
#: The finding is dropped when the same file also matches this pattern
|
|
26
|
+
#: (for example a mark test next to a letter test).
|
|
27
|
+
unless_in_file: re.Pattern[str] | None = None
|
|
28
|
+
#: The finding is dropped when the matched line also matches this.
|
|
29
|
+
unless_line: re.Pattern[str] | None = None
|
|
30
|
+
#: The finding is kept only when the matched line also matches this.
|
|
31
|
+
only_if_line: re.Pattern[str] | None = None
|
|
32
|
+
tags: tuple[str, ...] = field(default=())
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
ALL = frozenset({"js", "py", "go", "rs"})
|
|
36
|
+
|
|
37
|
+
# A generic word pattern (one that splits or matches human words, not a fixed
|
|
38
|
+
# token): \w+ or \W+ or \w*, a class of \w with ' or -, or \b next to \w.
|
|
39
|
+
_W = r"\\{1,2}"
|
|
40
|
+
_GENERIC_WORD = (
|
|
41
|
+
r"(?:" + _W + r"[wW][+*]"
|
|
42
|
+
r"|\[" + _W + r"w['\s\-]*\][+*]"
|
|
43
|
+
r"|" + _W + r"b" + _W + r"w"
|
|
44
|
+
r"|" + _W + r"w[+*]?" + _W + r"b)"
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
TEXTY = (
|
|
48
|
+
r"(?:name|title|text|label|caption|summary|snippet|desc|description|message|msg|"
|
|
49
|
+
r"comment|bio|address|city|content|body|preview|subject|headline|query|search)"
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
RULES: list[Rule] = [
|
|
53
|
+
Rule(
|
|
54
|
+
id="MAT001",
|
|
55
|
+
name="ascii-word-class",
|
|
56
|
+
languages=frozenset({"js", "py", "go"}),
|
|
57
|
+
pattern=re.compile(
|
|
58
|
+
r"(?:/[^/\n]*" + _GENERIC_WORD + r"[^/\n]*/[a-z]*" # JS regex literal
|
|
59
|
+
r"|(?:RegExp|re\.\w+|regexp\.\w+|regex\.\w+)\s*\([^)\n]*" + _GENERIC_WORD + r")"
|
|
60
|
+
),
|
|
61
|
+
# An address, handle or file-format pattern is ASCII by design.
|
|
62
|
+
unless_line=re.compile(r"@|https?:|\\.\w{2,4}\b|<\\?/?"),
|
|
63
|
+
confidence="medium",
|
|
64
|
+
message=r"\w and \b do not count Indian-script vowel signs as word characters, so words are shattered or never matched.",
|
|
65
|
+
evidence=(
|
|
66
|
+
"Python: re.findall(r'\\w+', 'हिंदी') == ['ह', 'द']. "
|
|
67
|
+
"JavaScript: 'हिंदी'.match(/\\w+/gu) is null, and \\b finds no boundary in 'தமிழ்'."
|
|
68
|
+
),
|
|
69
|
+
fix={
|
|
70
|
+
"py": r"Use the `regex` module with [\p{L}\p{M}\p{N}_]+ (and lookarounds instead of \b).",
|
|
71
|
+
"js": r"Use /[\p{L}\p{M}\p{N}_]+/u, and (?<![\p{L}\p{M}\p{N}_]) instead of \b.",
|
|
72
|
+
"go": r"Use [\p{L}\p{M}\p{N}_]+ instead of \w (RE2 supports \p classes).",
|
|
73
|
+
},
|
|
74
|
+
tags=("regex",),
|
|
75
|
+
),
|
|
76
|
+
Rule(
|
|
77
|
+
id="MAT002",
|
|
78
|
+
name="letters-without-marks",
|
|
79
|
+
languages=ALL,
|
|
80
|
+
pattern=re.compile(
|
|
81
|
+
r"\[[^\]\n]*\\\\?p\{(?:L|Letter|Lo|Lu|Ll)\}(?![^\]\n]*\\\\?p\{(?:M|Mark|Mn|Mc)\})[^\]\n]*\][+*]"
|
|
82
|
+
),
|
|
83
|
+
confidence="high",
|
|
84
|
+
message=r"A run of \p{L} stops at every vowel sign (\p{M}), so one word becomes several.",
|
|
85
|
+
evidence="JavaScript: 'हिंदी'.match(/[\\p{L}]+/gu) == ['ह', 'द']; 'தமிழ்' gives ['தம', 'ழ'].",
|
|
86
|
+
fix={lang: r"Add \p{M} to the class: [\p{L}\p{M}...]+." for lang in ALL},
|
|
87
|
+
tags=("regex",),
|
|
88
|
+
),
|
|
89
|
+
Rule(
|
|
90
|
+
id="MAT003",
|
|
91
|
+
name="isalpha-rejects-indic",
|
|
92
|
+
languages=frozenset({"py"}),
|
|
93
|
+
pattern=re.compile(r"\.(?:isalpha|isalnum)\(\)"),
|
|
94
|
+
only_if_line=re.compile(r"(?i)" + TEXTY + r"|word|input|token|value|surname|\bs\b|\btext\b"),
|
|
95
|
+
confidence="high",
|
|
96
|
+
message="str.isalpha() and str.isalnum() are False for every word with a vowel sign, so validation rejects names written in Indian scripts.",
|
|
97
|
+
evidence="'हिंदी'.isalpha(), 'தமிழ்'.isalpha(), 'বাংলা'.isalpha() and 'ਪੰਜਾਬੀ'.isalpha() are all False.",
|
|
98
|
+
fix={"py": r"Test per grapheme, or use regex.fullmatch(r'[\p{L}\p{M}]+', s) for letters."},
|
|
99
|
+
tags=("validation",),
|
|
100
|
+
),
|
|
101
|
+
Rule(
|
|
102
|
+
id="MAT004",
|
|
103
|
+
name="go-isletter-without-ismark",
|
|
104
|
+
languages=frozenset({"go"}),
|
|
105
|
+
pattern=re.compile(r"unicode\.Is(?:Letter|L)\b"),
|
|
106
|
+
confidence="medium",
|
|
107
|
+
message="unicode.IsLetter is false for vowel signs; splitting or validating words with it breaks Indian-script words.",
|
|
108
|
+
evidence="unicode.IsLetter('ि') is false (category Mc), so strings.FieldsFunc(s, notLetter) splits 'हिंदी' into 'ह' and 'द'.",
|
|
109
|
+
fix={"go": "Treat unicode.IsMark(r) as part of a word: unicode.IsLetter(r) || unicode.IsMark(r)."},
|
|
110
|
+
unless_in_file=re.compile(r"unicode\.(?:IsMark|M\b|Mn\b|Mc\b)"),
|
|
111
|
+
tags=("validation",),
|
|
112
|
+
),
|
|
113
|
+
Rule(
|
|
114
|
+
id="MAT005",
|
|
115
|
+
name="ascii-only-name-pattern",
|
|
116
|
+
languages=ALL,
|
|
117
|
+
pattern=re.compile(r"\[\^?(?:A-Za-z|a-zA-Z)[^\]\n]*\]"),
|
|
118
|
+
only_if_line=re.compile(r"(?i)(?:first|last|full|user|display|person|customer)?_?name|city|address|state"),
|
|
119
|
+
unless_line=re.compile(r"(?i)secret|token|key|hash|hex|uuid|slug|env|header|var_?name|file_?name|class_?name|tag_?name"),
|
|
120
|
+
confidence="medium",
|
|
121
|
+
message="An [A-Za-z] pattern on a name or place field rejects every name written in an Indian script.",
|
|
122
|
+
evidence="/^[a-zA-Z ]+$/.test('प्रिया') is false.",
|
|
123
|
+
fix={lang: r"Allow letters and marks from any script: ^[\p{L}\p{M} .'-]+$ (u flag in JS, `regex` in Python)." for lang in ALL},
|
|
124
|
+
tags=("validation",),
|
|
125
|
+
),
|
|
126
|
+
Rule(
|
|
127
|
+
id="MAT006",
|
|
128
|
+
name="truncation-splits-syllables",
|
|
129
|
+
languages=ALL,
|
|
130
|
+
pattern=re.compile(
|
|
131
|
+
r"(?i)\b\w*" + TEXTY + r"\w*\s*(?:"
|
|
132
|
+
r"\.(?:slice|substring|substr)\(\s*0\s*," # js
|
|
133
|
+
r"|\[\s*:\s*[\w.]+\s*\]" # py / go
|
|
134
|
+
r"|\[\s*\.\.\s*[\w.]+\s*\]" # rs
|
|
135
|
+
r")"
|
|
136
|
+
),
|
|
137
|
+
confidence="low",
|
|
138
|
+
message="Cutting text at a fixed index can split a syllable, leaving a dangling vowel sign or virama (and in Rust a byte index can panic).",
|
|
139
|
+
evidence="Python: 'क्षमा'[:2] == 'क्' (half a conjunct). Rust: &\"हिंदी\"[..4] panics (not a char boundary).",
|
|
140
|
+
fix={
|
|
141
|
+
"py": r"Cut at grapheme clusters: ''.join(regex.findall(r'\X', s)[:n]).",
|
|
142
|
+
"js": "Cut at grapheme clusters: [...new Intl.Segmenter().segment(s)].slice(0, n).map(x => x.segment).join('').",
|
|
143
|
+
"go": "Cut at grapheme clusters (github.com/rivo/uniseg), never with s[:n] on a string.",
|
|
144
|
+
"rs": "Cut at grapheme clusters with unicode-segmentation: s.graphemes(true).take(n).collect::<String>().",
|
|
145
|
+
},
|
|
146
|
+
tags=("truncation",),
|
|
147
|
+
),
|
|
148
|
+
Rule(
|
|
149
|
+
id="MAT007",
|
|
150
|
+
name="per-character-reversal",
|
|
151
|
+
languages=ALL,
|
|
152
|
+
pattern=re.compile(
|
|
153
|
+
r"""\.split\(\s*(["'])\1\s*\)\s*\.reverse\(\)"""
|
|
154
|
+
r"|\[\.\.\.\w+\]\.reverse\(\)"
|
|
155
|
+
r"|(?i:\b\w*" + TEXTY + r"\w*|\bword\w*|\bs\b|\bstring\w*)\[\s*::\s*-1\s*\]"
|
|
156
|
+
r"|\.chars\(\)\s*\.rev\(\)"
|
|
157
|
+
),
|
|
158
|
+
confidence="low",
|
|
159
|
+
message="Reversing code points moves vowel signs onto the wrong consonant.",
|
|
160
|
+
evidence="Python: 'हिंदी'[::-1] == 'ीदंिह', which starts with an orphan vowel sign.",
|
|
161
|
+
fix={lang: "Reverse grapheme clusters, not code points." for lang in ALL},
|
|
162
|
+
tags=("transform",),
|
|
163
|
+
),
|
|
164
|
+
]
|
|
165
|
+
|
|
166
|
+
BY_ID = {rule.id: rule for rule in RULES}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""Walk a tree, run the rules on each source line, and collect findings."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Iterable, Iterator
|
|
10
|
+
|
|
11
|
+
from .rules import RULES, Rule
|
|
12
|
+
|
|
13
|
+
EXTENSIONS = {
|
|
14
|
+
".js": "js", ".jsx": "js", ".mjs": "js", ".cjs": "js", ".ts": "js", ".tsx": "js", ".mts": "js", ".cts": "js",
|
|
15
|
+
".py": "py",
|
|
16
|
+
".go": "go",
|
|
17
|
+
".rs": "rs",
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
SKIP_DIRS = {
|
|
21
|
+
".git", "node_modules", "dist", "build", "target", ".venv", "venv", "__pycache__",
|
|
22
|
+
".next", ".nuxt", "vendor", "coverage", ".tox", ".mypy_cache", ".pytest_cache",
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
CONFIDENCE_ORDER = {"low": 0, "medium": 1, "high": 2}
|
|
26
|
+
|
|
27
|
+
# `matra: ignore` or `matra: ignore[MAT003, MAT006]` in a comment on the line.
|
|
28
|
+
_IGNORE = re.compile(r"matra:\s*ignore(?:\[([A-Z0-9,\s]+)\])?")
|
|
29
|
+
_COMMENT_START = {"js": "//", "go": "//", "rs": "//", "py": "#"}
|
|
30
|
+
_MAX_BYTES = 2_000_000
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class Finding:
|
|
35
|
+
rule: Rule
|
|
36
|
+
path: str
|
|
37
|
+
line: int
|
|
38
|
+
column: int
|
|
39
|
+
snippet: str
|
|
40
|
+
language: str
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def fix(self) -> str:
|
|
44
|
+
return self.rule.fix.get(self.language, next(iter(self.rule.fix.values())))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def language_of(path: Path) -> str | None:
|
|
48
|
+
return EXTENSIONS.get(path.suffix.lower())
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def iter_files(paths: Iterable[str | os.PathLike[str]]) -> Iterator[Path]:
|
|
52
|
+
for root in paths:
|
|
53
|
+
root = Path(root)
|
|
54
|
+
if root.is_file():
|
|
55
|
+
if language_of(root):
|
|
56
|
+
yield root
|
|
57
|
+
continue
|
|
58
|
+
for dirpath, dirnames, filenames in os.walk(root):
|
|
59
|
+
dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIRS and not d.startswith("."))
|
|
60
|
+
for name in sorted(filenames):
|
|
61
|
+
p = Path(dirpath, name)
|
|
62
|
+
if language_of(p) and not name.endswith((".min.js", ".d.ts")):
|
|
63
|
+
yield p
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _is_comment(line: str, language: str) -> bool:
|
|
67
|
+
stripped = line.lstrip()
|
|
68
|
+
return stripped.startswith(_COMMENT_START[language]) or (language != "py" and stripped.startswith("*"))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _ignored(line: str, rule_id: str) -> bool:
|
|
72
|
+
m = _IGNORE.search(line)
|
|
73
|
+
if not m:
|
|
74
|
+
return False
|
|
75
|
+
listed = m.group(1)
|
|
76
|
+
return listed is None or rule_id in {part.strip() for part in listed.split(",")}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def scan_text(text: str, path: str, language: str, rules: list[Rule] | None = None) -> list[Finding]:
|
|
80
|
+
# `matra: ignore-file` in the first 10 lines skips the file (fixtures, rule data).
|
|
81
|
+
if any("matra: ignore-file" in line for line in text.splitlines()[:10]):
|
|
82
|
+
return []
|
|
83
|
+
rules = [r for r in (rules or RULES) if language in r.languages]
|
|
84
|
+
rules = [r for r in rules if r.unless_in_file is None or not r.unless_in_file.search(text)]
|
|
85
|
+
findings: list[Finding] = []
|
|
86
|
+
for number, line in enumerate(text.splitlines(), start=1):
|
|
87
|
+
if _is_comment(line, language):
|
|
88
|
+
continue
|
|
89
|
+
for rule in rules:
|
|
90
|
+
m = rule.pattern.search(line)
|
|
91
|
+
if not m:
|
|
92
|
+
continue
|
|
93
|
+
if rule.only_if_line is not None and not rule.only_if_line.search(line):
|
|
94
|
+
continue
|
|
95
|
+
if rule.unless_line is not None and rule.unless_line.search(line):
|
|
96
|
+
continue
|
|
97
|
+
if _ignored(line, rule.id):
|
|
98
|
+
continue
|
|
99
|
+
findings.append(Finding(rule, path, number, m.start() + 1, line.strip()[:200], language))
|
|
100
|
+
return findings
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def scan(paths: Iterable[str | os.PathLike[str]], select: set[str] | None = None,
|
|
104
|
+
ignore: set[str] | None = None, min_confidence: str = "low") -> list[Finding]:
|
|
105
|
+
floor = CONFIDENCE_ORDER[min_confidence]
|
|
106
|
+
rules = [
|
|
107
|
+
r for r in RULES
|
|
108
|
+
if (not select or r.id in select)
|
|
109
|
+
and r.id not in (ignore or set())
|
|
110
|
+
and CONFIDENCE_ORDER[r.confidence] >= floor
|
|
111
|
+
]
|
|
112
|
+
out: list[Finding] = []
|
|
113
|
+
for file in iter_files(paths):
|
|
114
|
+
try:
|
|
115
|
+
if file.stat().st_size > _MAX_BYTES:
|
|
116
|
+
continue
|
|
117
|
+
text = file.read_text(encoding="utf-8", errors="replace")
|
|
118
|
+
except OSError:
|
|
119
|
+
continue
|
|
120
|
+
out.extend(scan_text(text, str(file), language_of(file) or "", rules))
|
|
121
|
+
return out
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import re
|
|
2
|
+
|
|
3
|
+
import regex
|
|
4
|
+
|
|
5
|
+
from matra.fuzz import check_tokenize, check_truncate, check_validator, graphemes
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def naive_truncate(text, n):
|
|
9
|
+
return text[:n]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def safe_truncate(text, n):
|
|
13
|
+
return "".join(graphemes(text)[:n])
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def naive_tokenize(text):
|
|
17
|
+
return re.findall(r"\w+", text)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def safe_tokenize(text):
|
|
21
|
+
return regex.findall(r"[\p{L}\p{M}\p{N}_]+", text)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def naive_valid_name(name):
|
|
25
|
+
return name.replace(" ", "").isalpha()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def safe_valid_name(name):
|
|
29
|
+
return regex.fullmatch(r"[\p{L}\p{M} .'-]+", name) is not None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def test_naive_functions_are_caught():
|
|
33
|
+
assert check_truncate(naive_truncate)
|
|
34
|
+
assert check_tokenize(naive_tokenize)
|
|
35
|
+
assert len(check_validator(naive_valid_name)) == 9 # every Indian-script name is rejected
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_correct_functions_pass():
|
|
39
|
+
assert check_truncate(safe_truncate) == []
|
|
40
|
+
assert check_tokenize(safe_tokenize) == []
|
|
41
|
+
assert check_validator(safe_valid_name) == []
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_a_crash_is_reported_not_raised():
|
|
45
|
+
def boom(text, n):
|
|
46
|
+
raise ValueError("no")
|
|
47
|
+
|
|
48
|
+
problems = check_truncate(boom, words=["हिंदी"])
|
|
49
|
+
assert problems and "ValueError" in str(problems[0].output)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def test_conjunct_is_one_cluster():
|
|
53
|
+
assert graphemes("क्षमा") == ["क्ष", "मा"]
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import re
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
from matra.cli import _sarif, main
|
|
7
|
+
from matra.scanner import scan, scan_text
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def ids(code: str, lang: str) -> list[str]:
|
|
11
|
+
return [f.rule.id for f in scan_text(code, "x", lang)]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
# (rule, language, code that must be flagged, code that must not be)
|
|
15
|
+
CASES = [
|
|
16
|
+
("MAT001", "py", r"words = re.findall(r'\w+', text)", r"words = regex.findall(r'[\p{L}\p{M}\p{N}_]+', text)"),
|
|
17
|
+
("MAT001", "js", r"const words = text.match(/\w+/gu);", r"const words = text.match(/[\p{L}\p{M}\p{N}_]+/gu);"),
|
|
18
|
+
("MAT001", "js", r"const re = new RegExp('\\b\\w+\\b', 'g');", r"const re = new RegExp('\\bfoo\\b');"),
|
|
19
|
+
("MAT001", "go", r'var word = regexp.MustCompile(`\w+`)', r'var word = regexp.MustCompile(`[\p{L}\p{M}\p{N}_]+`)'),
|
|
20
|
+
("MAT002", "js", r"const runs = s.match(/[\p{L}]+/gu);", r"const runs = s.match(/[\p{L}\p{M}]+/gu);"),
|
|
21
|
+
("MAT002", "rs", 'let re = Regex::new(r"[\\p{L}\\p{N}]+").unwrap();', 'let re = Regex::new(r"[\\p{L}\\p{M}\\p{N}]+").unwrap();'),
|
|
22
|
+
("MAT003", "py", "if not name.isalpha():", "if not name.isdigit():"),
|
|
23
|
+
("MAT005", "js", "if (!/^[a-zA-Z ]+$/.test(firstName)) throw err;", "if (!/^[0-9]+$/.test(pin)) throw err;"),
|
|
24
|
+
("MAT005", "py", "NAME_RE = re.compile(r'^[A-Za-z .]+$')", "PIN_RE = re.compile(r'^[0-9]{6}$')"),
|
|
25
|
+
("MAT006", "js", "const short = title.slice(0, 40);", "const firstTwo = items.slice(0, 2);"),
|
|
26
|
+
("MAT006", "py", "preview = description[:120]", "head = rows[:120]"),
|
|
27
|
+
("MAT006", "rs", "let s = &name[..max_len];", "let s = &bytes[..max_len];"),
|
|
28
|
+
("MAT007", "py", "mirrored = word[::-1]", "mirrored = list(reversed(items))"),
|
|
29
|
+
("MAT007", "js", "const r = s.split('').reverse().join('');", "const r = arr.reverse();"),
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@pytest.mark.parametrize("rule,lang,bad,good", CASES)
|
|
34
|
+
def test_rule_flags_bad_and_spares_good(rule, lang, bad, good):
|
|
35
|
+
assert rule in ids(bad, lang), bad
|
|
36
|
+
assert rule not in ids(good, lang), good
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def test_rust_word_class_is_not_flagged_because_rust_w_includes_marks():
|
|
40
|
+
assert "MAT001" not in ids('let re = Regex::new(r"\\w+").unwrap();', "rs")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def test_go_isletter_is_flagged_unless_the_file_also_checks_marks():
|
|
44
|
+
bad = "func ok(r rune) bool { return unicode.IsLetter(r) }"
|
|
45
|
+
assert "MAT004" in ids(bad, "go")
|
|
46
|
+
assert "MAT004" not in ids(bad + "\nfunc m(r rune) bool { return unicode.IsMark(r) }", "go")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def test_comments_and_inline_ignores_are_skipped():
|
|
50
|
+
assert ids("# name.isalpha() is wrong here", "py") == []
|
|
51
|
+
assert ids("ok = name.isalpha() # matra: ignore", "py") == []
|
|
52
|
+
assert ids("ok = name.isalpha() # matra: ignore[MAT003]", "py") == []
|
|
53
|
+
assert ids("ok = name.isalpha() # matra: ignore[MAT006]", "py") == ["MAT003"]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def test_the_evidence_in_the_rules_is_true():
|
|
57
|
+
# The rules' claims, checked against this Python.
|
|
58
|
+
assert re.findall(r"\w+", "हिंदी") == ["ह", "द"]
|
|
59
|
+
assert not "हिंदी".isalpha() and not "தமிழ்".isalpha() and not "বাংলা".isalpha() and not "ਪੰਜਾਬੀ".isalpha()
|
|
60
|
+
assert "क्षमा"[:2] == "क््"[:2]
|
|
61
|
+
assert "हिंदी"[::-1] == "ीदंिह"
|
|
62
|
+
assert re.fullmatch(r"[a-zA-Z ]+", "प्रिया") is None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def test_scan_walks_a_tree_and_skips_vendored_dirs(tmp_path):
|
|
66
|
+
(tmp_path / "app.py").write_text("ok = name.isalpha()\n", encoding="utf-8")
|
|
67
|
+
(tmp_path / "node_modules").mkdir()
|
|
68
|
+
(tmp_path / "node_modules" / "dep.js").write_text("x.match(/\\w+/)\n", encoding="utf-8")
|
|
69
|
+
(tmp_path / "notes.txt").write_text("name.isalpha()\n", encoding="utf-8")
|
|
70
|
+
found = scan([tmp_path])
|
|
71
|
+
assert [(f.rule.id, f.path.endswith("app.py")) for f in found] == [("MAT003", True)]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def test_min_confidence_and_select_filter(tmp_path):
|
|
75
|
+
(tmp_path / "a.py").write_text("ok = name.isalpha()\npreview = title[:10]\n", encoding="utf-8")
|
|
76
|
+
assert {f.rule.id for f in scan([tmp_path])} == {"MAT003", "MAT006"}
|
|
77
|
+
assert {f.rule.id for f in scan([tmp_path], min_confidence="medium")} == {"MAT003"}
|
|
78
|
+
assert {f.rule.id for f in scan([tmp_path], select={"MAT006"})} == {"MAT006"}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def test_sarif_is_well_formed(tmp_path):
|
|
82
|
+
(tmp_path / "a.py").write_text("ok = name.isalpha()\n", encoding="utf-8")
|
|
83
|
+
doc = _sarif(scan([tmp_path]))
|
|
84
|
+
run = doc["runs"][0]
|
|
85
|
+
assert doc["version"] == "2.1.0"
|
|
86
|
+
assert run["tool"]["driver"]["rules"][0]["id"] == "MAT003"
|
|
87
|
+
assert run["results"][0]["locations"][0]["physicalLocation"]["region"]["startLine"] == 1
|
|
88
|
+
json.dumps(doc)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def test_cli_exit_codes(tmp_path, capsys):
|
|
92
|
+
(tmp_path / "a.py").write_text("ok = name.isalpha()\n", encoding="utf-8")
|
|
93
|
+
assert main(["check", str(tmp_path)]) == 1
|
|
94
|
+
assert main(["check", str(tmp_path), "--exit-zero"]) == 0
|
|
95
|
+
assert main(["check", str(tmp_path), "--ignore", "MAT003"]) == 0
|
|
96
|
+
assert main(["demo"]) == 0
|
|
97
|
+
assert "हिंदी" in capsys.readouterr().out
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
# Precision: patterns seen in real projects that are ASCII by design.
|
|
101
|
+
NOT_FLAGGED = [
|
|
102
|
+
("py", r"vpas = re.findall(r'\b[\w.\-]+@[\w]+\b', page)"), # UPI IDs are ASCII
|
|
103
|
+
("js", r'return text.replace(/\bClipy\b(?! Local)/g, "Clipy Local");'), # a fixed word
|
|
104
|
+
("js", r"if (/^DirectShow audio devices\b/i.test(body)) {"), # tool output
|
|
105
|
+
("js", r"const select = markup.match(/<select\b[^>]*>/)?.[0];"), # markup
|
|
106
|
+
("py", "return len(g) == 15 and g[:14].isalnum()"), # a GSTIN, ASCII by spec
|
|
107
|
+
]
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@pytest.mark.parametrize("lang,code", NOT_FLAGGED)
|
|
111
|
+
def test_ascii_by_design_patterns_are_not_flagged(lang, code):
|
|
112
|
+
assert [i for i in ids(code, lang) if i in {"MAT001", "MAT003"}] == []
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def test_list_reversal_and_key_patterns_are_not_flagged():
|
|
116
|
+
assert "MAT007" not in ids("for i, o in enumerate(ops[::-1]):", "py")
|
|
117
|
+
assert "MAT007" in ids("backwards = title[::-1]", "py")
|
|
118
|
+
assert "MAT005" not in ids("const SECRET_KEY_FRAGMENT = `[A-Za-z0-9_-]*(?:${SECRET_KEY_NAMES})`;", "js")
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def test_ignore_file_directive():
|
|
122
|
+
assert ids("# matra: ignore-file\nok = name.isalpha()\n", "py") == []
|