printer-claim-audit 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,158 @@
1
+ """Static local hardcopy job submission audit."""
2
+ import ast
3
+ import fnmatch
4
+ import os
5
+ import re
6
+ from pathlib import Path
7
+ from .phrases import PRINTER, NOPRINTER
8
+
9
+ __version__ = '0.1.0'
10
+
11
+
12
+ def normalize(text):
13
+ return re.sub(r'\s+', ' ', text.lower().replace("n't", ' not').replace('-', ' ')).strip()
14
+
15
+
16
+ def claims(text):
17
+ paragraphs = []
18
+ lines = []
19
+ fence = None
20
+ for line in text.splitlines():
21
+ mark = re.match(r'^\s{0,3}(`{3,}|~{3,})', line)
22
+ if mark:
23
+ token = mark.group(1)
24
+ if fence is None:
25
+ fence = token
26
+ elif token[0] == fence[0] and len(token) >= len(fence):
27
+ fence = None
28
+ continue
29
+ if fence is not None:
30
+ continue
31
+ if not line.strip():
32
+ paragraphs.append(normalize(' '.join(lines)))
33
+ lines = []
34
+ else:
35
+ lines.append(line)
36
+ paragraphs.append(normalize(' '.join(lines)))
37
+ positive = negative = False
38
+ for paragraph in paragraphs:
39
+ for phrase in sorted(NOPRINTER, key=len, reverse=True):
40
+ paragraph, count = re.subn(r'\b' + re.escape(phrase) + r'\b', ' ', paragraph)
41
+ negative |= bool(count)
42
+ positive |= any(re.search(r'\b' + re.escape(phrase) + r'\b', paragraph) for phrase in PRINTER)
43
+ return positive, negative
44
+
45
+
46
+ def dotted(node):
47
+ if isinstance(node, ast.Name):
48
+ return node.id
49
+ if isinstance(node, ast.Attribute):
50
+ base = dotted(node.value)
51
+ return base + '.' + node.attr if base else ''
52
+ return ''
53
+
54
+
55
+ def evidence(source):
56
+ """Resolve provider constructors and submission calls within one module."""
57
+ tree = ast.parse(source)
58
+ aliases = {}
59
+ for node in ast.walk(tree):
60
+ if isinstance(node, ast.Import):
61
+ for alias in node.names:
62
+ aliases[alias.asname or alias.name.split('.')[0]] = alias.name if alias.asname else alias.name.split('.')[0]
63
+ elif isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
64
+ for alias in node.names:
65
+ aliases[alias.asname or alias.name] = node.module + '.' + alias.name
66
+
67
+ def resolve(node):
68
+ path = dotted(node)
69
+ first, sep, rest = path.partition('.')
70
+ return aliases.get(first, first) + (sep + rest if sep else '') if path else ''
71
+
72
+ def constructor(node):
73
+ if not isinstance(node, ast.Call):
74
+ return None
75
+ path = resolve(node.func)
76
+ module, _, name = path.rpartition('.')
77
+ if (module == 'cups' or module.startswith('cups.')) and name == 'Connection':
78
+ return 'cups'
79
+ if (module == 'win32print' or module.startswith('win32print.')) and name == 'OpenPrinter':
80
+ return 'win32print'
81
+ if (module == 'escpos.printer' or module.startswith('escpos.printer.')) and name in {'Usb', 'Network', 'Serial', 'File'}:
82
+ return 'escpos'
83
+ return None
84
+
85
+ bindings = {}
86
+ for node in ast.walk(tree):
87
+ if isinstance(node, ast.Assign):
88
+ provider = constructor(node.value)
89
+ if provider:
90
+ for target in node.targets:
91
+ if isinstance(target, ast.Name) or (isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name) and target.value.id == 'self'):
92
+ bindings[dotted(target)] = provider
93
+
94
+ def bound(node, provider):
95
+ return constructor(node) == provider or (isinstance(node, (ast.Name, ast.Attribute)) and bindings.get(dotted(node)) == provider)
96
+
97
+ found = []
98
+ for node in ast.walk(tree):
99
+ if not isinstance(node, ast.Call):
100
+ continue
101
+ func = node.func
102
+ route = None
103
+ if isinstance(func, ast.Attribute):
104
+ if func.attr in {'printFile', 'printFiles'} and bound(func.value, 'cups'):
105
+ route = 'cups'
106
+ elif func.attr in {'text', 'image', 'cut', 'qr', 'barcode'} and bound(func.value, 'escpos'):
107
+ route = 'escpos'
108
+ path = resolve(func)
109
+ module, _, name = path.rpartition('.')
110
+ if name == 'WritePrinter' and (module == 'win32print' or module.startswith('win32print.')) and node.args and bound(node.args[0], 'win32print'):
111
+ route = 'win32print'
112
+ if route:
113
+ found.append({'line': node.lineno, 'provider': route})
114
+ return found
115
+
116
+
117
+ def audit(root, ignore=(), fail_on='HIGH'):
118
+ root = Path(root)
119
+ if not root.is_dir() or not os.access(root, os.R_OK | os.X_OK):
120
+ raise ValueError('root must be a readable directory')
121
+ positive = negative = False
122
+ production = []
123
+ test_evidence = []
124
+ errors = []
125
+ for directory, dirs, files in os.walk(root, followlinks=False):
126
+ dirs[:] = sorted(d for d in dirs if not (Path(directory) / d).is_symlink())
127
+ for filename in sorted(files):
128
+ path = Path(directory) / filename
129
+ rel = path.relative_to(root)
130
+ name = rel.as_posix()
131
+ if path.is_symlink() or any(fnmatch.fnmatchcase(name, pattern) for pattern in ignore):
132
+ continue
133
+ is_doc = name == 'README.md' or (path.suffix.lower() == '.md' and 'docs' in rel.parts[:-1])
134
+ if is_doc:
135
+ a, b = claims(path.read_text(encoding='utf-8'))
136
+ positive |= a
137
+ negative |= b
138
+ if path.suffix != '.py':
139
+ continue
140
+ parts = rel.parts[:-1]
141
+ if any(p in {'fixtures', 'docs', 'examples'} for p in parts):
142
+ continue
143
+ test = 'tests' in parts or filename.startswith('test_') or filename.endswith('_test.py')
144
+ try:
145
+ hits = evidence(path.read_text(encoding='utf-8'))
146
+ except (SyntaxError, UnicodeError) as exc:
147
+ errors.append({'path': name, 'message': str(exc)})
148
+ continue
149
+ for hit in hits:
150
+ hit['path'] = name
151
+ (test_evidence if test else production).append(hit)
152
+ findings = []
153
+ if positive and not production:
154
+ findings.append({'rule': 'documented-printer-claim-false', 'severity': 'MEDIUM' if test_evidence else 'HIGH', 'message': 'Local-job claim lacks production submission evidence.'})
155
+ if negative and production:
156
+ findings.append({'rule': 'documented-no-printer-claim-false', 'severity': 'HIGH', 'message': 'Local-job denial conflicts with production submission evidence.'})
157
+ failed = any(f['severity'] == 'HIGH' or fail_on == 'MEDIUM' for f in findings)
158
+ return {'verdict': 'FAIL' if failed else 'PASS', 'findings': findings, 'evidence': production, 'test_evidence': test_evidence, 'parse_errors': errors, 'claims': {'positive': positive, 'negative': negative}}
@@ -0,0 +1,40 @@
1
+ import argparse
2
+ import json
3
+ import sys
4
+ from . import __version__, audit
5
+
6
+
7
+ class Parser(argparse.ArgumentParser):
8
+ def error(self, message):
9
+ self.print_usage(sys.stderr)
10
+ self.exit(1, self.prog + ': error: ' + message + '\n')
11
+
12
+
13
+ def main(argv=None):
14
+ parser = Parser(description='Audit local hardcopy job submission claims.')
15
+ parser.add_argument('root')
16
+ parser.add_argument('--json', action='store_true')
17
+ parser.add_argument('--verbose', action='store_true')
18
+ parser.add_argument('--ignore', action='append', default=[])
19
+ parser.add_argument('--fail-on', choices=['HIGH', 'MEDIUM'], default='HIGH')
20
+ parser.add_argument('--version', action='version', version=__version__)
21
+ args = parser.parse_args(argv)
22
+ try:
23
+ result = audit(args.root, args.ignore, args.fail_on)
24
+ except (OSError, ValueError) as exc:
25
+ parser.exit(1, 'error: ' + str(exc) + '\n')
26
+ if args.json:
27
+ print(json.dumps(result))
28
+ else:
29
+ print(result['verdict'])
30
+ for finding in result['findings']:
31
+ print('{severity} {rule}: {message}'.format(**finding))
32
+ if args.verbose:
33
+ for key in ('evidence', 'test_evidence', 'parse_errors'):
34
+ for item in result[key]:
35
+ print(key + ': ' + json.dumps(item))
36
+ return 2 if result['verdict'] == 'FAIL' else 0
37
+
38
+
39
+ if __name__ == '__main__':
40
+ sys.exit(main())
@@ -0,0 +1,2 @@
1
+ PRINTER = ('prints documents to your printer', 'print documents to your printer', 'prints files to your printer', 'print files to your printer', 'prints receipts to your printer', 'print receipts to your printer', 'prints labels to your printer', 'print labels to your printer', 'sends documents to your printer', 'send documents to your printer', 'sends files to your printer', 'send files to your printer', 'sends receipts to your printer', 'send receipts to your printer', 'prints to your printer', 'print to your printer', 'uses your printer to print', 'supports printer output', 'printer output support', 'supports direct printing', 'direct printing support', 'receipt printing support', 'label printing support', 'thermal printer support', 'supports thermal printing', 'prints documents', 'print documents', 'prints receipts', 'print receipts', 'prints labels', 'print labels')
2
+ NOPRINTER = ('does not print documents to your printer', 'does not print files to your printer', 'does not print receipts to your printer', 'does not print labels to your printer', 'does not send documents to your printer', 'does not print to your printer', 'does not use your printer', 'does not access your printer', 'printer output not supported', 'direct printing not supported', 'receipt printing not supported', 'label printing not supported', 'no printer output', 'no direct printing', 'without printer output', 'without direct printing', 'no printer support', 'no receipt printing')
@@ -0,0 +1,68 @@
1
+ Metadata-Version: 2.4
2
+ Name: printer-claim-audit
3
+ Version: 0.1.0
4
+ Summary: Static audit of local hardcopy job submission claims
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Dynamic: license-file
10
+
11
+ # printer-claim-audit
12
+
13
+ An offline static audit for local hardcopy job submission claims. It compares
14
+ root README.md and Markdown files beneath a docs path component against Python
15
+ AST evidence of attached printing device intake. Source is never executed.
16
+ No runtime dependencies are required. Python 3.9 or newer is required.
17
+
18
+ Install and run:
19
+
20
+ ```sh
21
+ python3 -m pip install .
22
+ printer-claim-audit /path/to/project --json
23
+ python3 -m printer_claim_audit /path/to/project --verbose
24
+ ```
25
+
26
+ Options: `--ignore <glob>` is repeatable and matches root-relative paths;
27
+ `--fail-on HIGH` is the default; `--fail-on MEDIUM` also fails on evidence
28
+ found only in test source. `--version` reports 0.1.0. JSON includes verdict,
29
+ findings, production and test evidence locations, claim flags, and parse errors.
30
+ Human output lists findings; verbose output also lists evidence and parse errors.
31
+ Exit 0 means PASS, exit 2 means findings meet the severity threshold, and exit 1
32
+ means invalid usage or an inaccessible root. Findings below the threshold remain
33
+ visible even when the verdict is PASS. At most one finding per claim family is emitted.
34
+
35
+ ## Limitations
36
+
37
+ Only the exact phrase templates in the package's `phrases.py` are recognized.
38
+ A bare device noun, tool name, dependency list, user instruction, console message,
39
+ PDF export, file save, screen grab, audio capture, or network send is outside
40
+ that vocabulary. Fenced blocks are excluded; inline code counts. Paragraphs are
41
+ normalized for case, contractions, hyphens, and whitespace. Denial spans are
42
+ removed before affirmative matching.
43
+
44
+ Evidence recognizes bound cups Connection job methods, win32print handle writes,
45
+ and escpos.printer object job methods. Imports, constructors alone, previews,
46
+ strings, comments, and docstrings do not establish capability. Shell spool helpers
47
+ such as lp, lpr, and lpstat are outside the recognized routes.
48
+
49
+ Bindings and aliases are module-local syntactic approximations; this tool does
50
+ not prove execution, device availability, delivery, control flow, or runtime name
51
+ identity. Syntax errors are reported and contribute no evidence. Test source can
52
+ reduce an unsupported affirmative assertion to MEDIUM; a denial contradicted by
53
+ production evidence is HIGH. An affirmative assertion without source is HIGH;
54
+ a denial without source passes. No recognized assertion means PASS.
55
+
56
+ Production excludes tests, test-named modules, fixtures, docs, examples, and
57
+ symlinked files or directories. Environment files are never opened. Ignore globs
58
+ apply to documentation and source. Markdown under any docs path component counts,
59
+ including documentation beneath test directories.
60
+
61
+ Run checks and build distributions:
62
+
63
+ ```sh
64
+ python3 -m unittest discover
65
+ python3 -m build
66
+ ```
67
+
68
+ The tests and fixtures are included in the source distribution. License: MIT.
@@ -0,0 +1,9 @@
1
+ printer_claim_audit/__init__.py,sha256=cBEUB09NukxWhRwFadlNNYqc1xQ_Ipox4ktPho6BdgU,6720
2
+ printer_claim_audit/__main__.py,sha256=KBY9bnzeYRBpXAWA31ERyAR1kqzQMLm8WPwfWvETjT0,1410
3
+ printer_claim_audit/phrases.py,sha256=TDS_uSWIilzZzxo2WEzk4WmtMPC_U4p2ILK2i2QSdPk,1475
4
+ printer_claim_audit-0.1.0.dist-info/licenses/LICENSE,sha256=a1VuJ-efh7ul8wfEGK1pWMwLIEdbzkENMJvpyUz-Sh8,1089
5
+ printer_claim_audit-0.1.0.dist-info/METADATA,sha256=3geI4inHRwhwBA4x3zdv0BASazF6DUM8XtNdfZg0Qpc,3068
6
+ printer_claim_audit-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ printer_claim_audit-0.1.0.dist-info/entry_points.txt,sha256=5LVb_A2KHHzqSM3Ta_iz4oX3DGuE689YVb4ncPZJWLU,74
8
+ printer_claim_audit-0.1.0.dist-info/top_level.txt,sha256=LXZZns2XrgrP_5FetsSvDi9hsLdodYaBcXCh4lWPqNI,20
9
+ printer_claim_audit-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ printer-claim-audit = printer_claim_audit.__main__:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 printer-claim-audit contributors
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 @@
1
+ printer_claim_audit