assert-no-comments 20260823131905__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 @@
1
+ """Assert that nothing in a tree carries a comment or a docstring."""
@@ -0,0 +1,5 @@
1
+ """Entry point for running as python -m assert_no_comments."""
2
+
3
+ from .cli import main
4
+
5
+ main()
@@ -0,0 +1,333 @@
1
+ """Command-line interface for assert-no-comments."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import fnmatch
7
+ import glob
8
+ import os
9
+ import sys
10
+ from dataclasses import dataclass, field
11
+ from typing import TYPE_CHECKING
12
+
13
+ from .scanner import Finding, Unreadable, comments_in, reader_for
14
+
15
+ if TYPE_CHECKING:
16
+ from collections.abc import Sequence
17
+
18
+ EXIT_SUCCESS = 0
19
+ EXIT_FINDINGS = 1
20
+ EXIT_ERROR = 2
21
+
22
+ GLOB_CHARACTERS = ("*", "?", "[")
23
+
24
+ SKIPPED_DIRECTORIES = (".git", "__pycache__", "node_modules")
25
+
26
+ MESSAGE = "carries a comment or a docstring; delete it and let the code say what it does"
27
+
28
+
29
+ @dataclass
30
+ class ScanResult:
31
+ """The outcome of one run over a set of trees."""
32
+
33
+ findings: list[Finding] = field(default_factory=list)
34
+ files_scanned: int = 0
35
+ had_error: bool = False
36
+
37
+
38
+ def create_parser() -> argparse.ArgumentParser:
39
+ """Create the argument parser for the CLI."""
40
+ parser = argparse.ArgumentParser(
41
+ prog="assert-no-comments",
42
+ description=(
43
+ "Assert that nothing in the given trees carries a comment or a docstring. "
44
+ "Prose beside code is never checked, so it stops being true and nothing says "
45
+ "when, and the reader who believes it works from a program that no longer "
46
+ "exists."
47
+ ),
48
+ )
49
+
50
+ parser.add_argument(
51
+ "trees",
52
+ nargs="+",
53
+ metavar="TREE",
54
+ help=(
55
+ "One or more file paths, directory paths, or glob patterns to read. "
56
+ "Directories are read recursively, and a file whose suffix names no "
57
+ "language this understands is left alone."
58
+ ),
59
+ )
60
+
61
+ parser.add_argument(
62
+ "--exclude",
63
+ metavar="PATTERNS",
64
+ help=(
65
+ "Comma-separated glob patterns to leave out, such as "
66
+ "'src/www/spa/vendor/*' for code somebody else wrote."
67
+ ),
68
+ )
69
+
70
+ parser.add_argument(
71
+ "--annotate",
72
+ action="store_true",
73
+ help=(
74
+ "Print each finding as a GitHub Actions ::error annotation, so it lands on "
75
+ "the line it names in the diff."
76
+ ),
77
+ )
78
+
79
+ output_group = parser.add_mutually_exclusive_group()
80
+ output_group.add_argument(
81
+ "--quiet",
82
+ action="store_true",
83
+ help="Suppress all output. Exit code indicates success (0) or findings (1).",
84
+ )
85
+ output_group.add_argument(
86
+ "--count",
87
+ action="store_true",
88
+ help="Output only the count of findings.",
89
+ )
90
+ output_group.add_argument(
91
+ "--verbose",
92
+ action="store_true",
93
+ help="Show the files read, the findings and a summary.",
94
+ )
95
+
96
+ behavior_group = parser.add_mutually_exclusive_group()
97
+ behavior_group.add_argument(
98
+ "--fail-fast",
99
+ action="store_true",
100
+ help="Exit immediately after finding the first comment.",
101
+ )
102
+ behavior_group.add_argument(
103
+ "--warn-only",
104
+ action="store_true",
105
+ help="Always exit with code 0, even if findings exist.",
106
+ )
107
+
108
+ return parser
109
+
110
+
111
+ def parse_patterns(patterns_str: str | None) -> list[str]:
112
+ """Parse a comma-separated patterns string.
113
+
114
+ Args:
115
+ patterns_str: Comma-separated patterns, or None.
116
+
117
+ Returns:
118
+ The patterns, empty when the input is None or blank.
119
+ """
120
+ if not patterns_str:
121
+ return []
122
+ return [pattern.strip() for pattern in patterns_str.split(",") if pattern.strip()]
123
+
124
+
125
+ def _is_glob_pattern(path: str) -> bool:
126
+ """Check whether a path holds glob wildcard characters."""
127
+ return any(character in path for character in GLOB_CHARACTERS)
128
+
129
+
130
+ def _walk_source_files(directory: str) -> list[str]:
131
+ """Find every file under a directory a reader speaks the language of."""
132
+ found: list[str] = []
133
+ for root, directories, filenames in os.walk(directory):
134
+ directories[:] = [name for name in directories if name not in SKIPPED_DIRECTORIES]
135
+ found.extend(
136
+ os.path.join(root, filename)
137
+ for filename in filenames
138
+ if reader_for(filename) is not None
139
+ )
140
+ return found
141
+
142
+
143
+ def _expand(path: str) -> tuple[list[str], bool]:
144
+ """Expand one path, directory or glob into the files it names.
145
+
146
+ Args:
147
+ path: A file path, directory path or glob pattern.
148
+
149
+ Returns:
150
+ The files it names, and whether it named anything at all.
151
+ """
152
+ if _is_glob_pattern(path):
153
+ matched = glob.glob(path, recursive=True, include_hidden=True)
154
+ found: list[str] = []
155
+ for entry in matched:
156
+ if os.path.isfile(entry):
157
+ found.append(entry)
158
+ elif os.path.isdir(entry):
159
+ found.extend(_walk_source_files(entry))
160
+ return (found, bool(matched))
161
+ if os.path.isfile(path):
162
+ return ([path], True)
163
+ if os.path.isdir(path):
164
+ return (_walk_source_files(path), True)
165
+ return ([], False)
166
+
167
+
168
+ def should_skip(path: str, exclude_patterns: list[str]) -> bool:
169
+ """Check whether a file matches any exclude pattern.
170
+
171
+ Args:
172
+ path: The file path to check.
173
+ exclude_patterns: Glob patterns to exclude.
174
+
175
+ Returns:
176
+ True when the path or its basename matches a pattern.
177
+ """
178
+ return any(
179
+ fnmatch.fnmatch(path, pattern) or fnmatch.fnmatch(os.path.basename(path), pattern)
180
+ for pattern in exclude_patterns
181
+ )
182
+
183
+
184
+ def collect(paths: Sequence[str], exclude_patterns: list[str]) -> tuple[list[str], list[str]]:
185
+ """Expand paths into the files to read.
186
+
187
+ Args:
188
+ paths: File paths, directory paths or glob patterns.
189
+ exclude_patterns: Glob patterns to exclude.
190
+
191
+ Returns:
192
+ The files to read, sorted and without repeats, and the paths that
193
+ named nothing.
194
+ """
195
+ found: set[str] = set()
196
+ missing: list[str] = []
197
+ for path in paths:
198
+ expanded, matched = _expand(path)
199
+ if not matched:
200
+ missing.append(path)
201
+ continue
202
+ for entry in expanded:
203
+ normalised = os.path.normpath(entry)
204
+ if reader_for(normalised) is not None and not should_skip(
205
+ normalised, exclude_patterns
206
+ ):
207
+ found.add(normalised)
208
+ return (sorted(found), missing)
209
+
210
+
211
+ def _read(path: str, result: ScanResult) -> str | None:
212
+ """Read one file, recording an error on the result if it cannot be read."""
213
+ try:
214
+ with open(path, encoding="utf-8") as handle:
215
+ return handle.read()
216
+ except (OSError, UnicodeDecodeError) as error:
217
+ print(f"Error reading {path}: {error}", file=sys.stderr)
218
+ result.had_error = True
219
+ return None
220
+
221
+
222
+ def read_comments(paths: Sequence[str], result: ScanResult, verbose: bool = False) -> list[Finding]:
223
+ """Read every file and collect the comments it carries.
224
+
225
+ Args:
226
+ paths: The files to read.
227
+ result: The result to record read errors and counts on.
228
+ verbose: Whether to name each file read.
229
+
230
+ Returns:
231
+ Every finding, in path order.
232
+ """
233
+ findings: list[Finding] = []
234
+ for path in paths:
235
+ content = _read(path, result)
236
+ if content is None:
237
+ continue
238
+ if verbose:
239
+ print(f"Reading: {path}")
240
+ try:
241
+ findings.extend(comments_in(path, content))
242
+ except Unreadable as error:
243
+ print(f"Could not parse {path}: {error}", file=sys.stderr)
244
+ result.had_error = True
245
+ continue
246
+ result.files_scanned += 1
247
+ return findings
248
+
249
+
250
+ def output_findings(
251
+ findings: list[Finding], count_mode: bool = False, annotate: bool = False
252
+ ) -> None:
253
+ """Print findings in the requested format.
254
+
255
+ Args:
256
+ findings: The findings to print.
257
+ count_mode: Print only how many there are.
258
+ annotate: Print each as a GitHub Actions ::error annotation.
259
+ """
260
+ if count_mode:
261
+ print(len(findings))
262
+ return
263
+ for finding in findings:
264
+ if annotate:
265
+ print(
266
+ f"::error file={finding.path},line={finding.line_number}::"
267
+ f"{finding} {MESSAGE}"
268
+ )
269
+ else:
270
+ print(f"{finding}: {MESSAGE}")
271
+
272
+
273
+ def determine_exit_code(result: ScanResult, warn_only: bool = False) -> int:
274
+ """Choose the exit code for a result.
275
+
276
+ Args:
277
+ result: The scan result.
278
+ warn_only: Always succeed when true.
279
+
280
+ Returns:
281
+ 0 for success, 1 for findings, 2 for errors.
282
+ """
283
+ if warn_only:
284
+ return EXIT_SUCCESS
285
+ if result.findings:
286
+ return EXIT_FINDINGS
287
+ if result.had_error:
288
+ return EXIT_ERROR
289
+ return EXIT_SUCCESS
290
+
291
+
292
+ def _report(result: ScanResult, args: argparse.Namespace) -> None:
293
+ """Print whatever the chosen output mode asks for."""
294
+ if args.quiet:
295
+ return
296
+ output_findings(result.findings, args.count, args.annotate)
297
+ if args.verbose:
298
+ print()
299
+ print(f"Files scanned: {result.files_scanned}")
300
+ print(f"Findings: {len(result.findings)}")
301
+ if result.had_error:
302
+ print("Errors occurred during scanning.")
303
+
304
+
305
+ def main(argv: Sequence[str] | None = None) -> None:
306
+ """Run the CLI.
307
+
308
+ Args:
309
+ argv: Command-line arguments, defaulting to sys.argv[1:].
310
+ """
311
+ args = create_parser().parse_args(argv)
312
+ exclude_patterns = parse_patterns(args.exclude)
313
+ result = ScanResult()
314
+
315
+ paths, missing = collect(args.trees, exclude_patterns)
316
+ for path in missing:
317
+ print(f"Error: Path not found: {path}", file=sys.stderr)
318
+ if not paths and missing:
319
+ sys.exit(EXIT_ERROR)
320
+ if missing:
321
+ result.had_error = True
322
+
323
+ if args.verbose:
324
+ print(f"Reading {len(paths)} file(s)...")
325
+ if exclude_patterns:
326
+ print(f"Excluding patterns: {', '.join(exclude_patterns)}")
327
+ print()
328
+
329
+ findings = read_comments(paths, result, args.verbose)
330
+ result.findings = findings[:1] if (args.fail_fast and findings) else findings
331
+
332
+ _report(result, args)
333
+ sys.exit(determine_exit_code(result, args.warn_only))
File without changes
@@ -0,0 +1,266 @@
1
+ """Readers that find every comment and docstring a source file carries."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import bisect
7
+ import io
8
+ import os
9
+ import tokenize
10
+ from dataclasses import dataclass
11
+ from typing import TYPE_CHECKING
12
+
13
+ import yaml
14
+
15
+ if TYPE_CHECKING:
16
+ from collections.abc import Callable
17
+
18
+ DEFINITION_NODES = (ast.AsyncFunctionDef, ast.ClassDef, ast.FunctionDef, ast.Module)
19
+
20
+ OPENS_A_PATTERN = "(,=:[!&|?{};+-*%~^<>"
21
+
22
+
23
+ class Unreadable(Exception):
24
+ """A file no reader could parse."""
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class Finding:
29
+ """A line carrying a comment or a docstring."""
30
+
31
+ path: str
32
+ line_number: int
33
+
34
+ def __str__(self) -> str:
35
+ """Format as path:line."""
36
+ return f"{self.path}:{self.line_number}"
37
+
38
+
39
+ def _lines_of(text: str, places: list[int]) -> list[int]:
40
+ """Turn character offsets into the one-based lines holding them."""
41
+ breaks = [place for place, character in enumerate(text) if character == "\n"]
42
+ return sorted({bisect.bisect_right(breaks, place) + 1 for place in places})
43
+
44
+
45
+ def _past_quoted(text: str, place: int) -> int:
46
+ """Step over a quoted string, honouring backslash escapes."""
47
+ quote = text[place]
48
+ place += 1
49
+ while place < len(text):
50
+ if text[place] == "\\":
51
+ place += 2
52
+ elif text[place] == quote:
53
+ return place + 1
54
+ else:
55
+ place += 1
56
+ return place
57
+
58
+
59
+ def _past_line(text: str, place: int) -> int:
60
+ """Step to the end of the line an offset sits on."""
61
+ end = text.find("\n", place)
62
+ return len(text) if end < 0 else end
63
+
64
+
65
+ def _past_block(text: str, place: int, closing: str) -> int:
66
+ """Step over a block comment, to the end of the file when nobody closed it."""
67
+ end = text.find(closing, place + len(closing))
68
+ return len(text) if end < 0 else end + len(closing)
69
+
70
+
71
+ def _opens_a_pattern(text: str, place: int) -> bool:
72
+ """Decide whether a slash starts a regular expression rather than a division."""
73
+ before = text[:place].rstrip()
74
+ return not before or before[-1] in OPENS_A_PATTERN or before.endswith("return")
75
+
76
+
77
+ def _past_pattern(text: str, place: int) -> int:
78
+ """Step over a regular expression literal, ending it at a line break."""
79
+ place += 1
80
+ inside_a_class = False
81
+ while place < len(text):
82
+ character = text[place]
83
+ if character == "\\":
84
+ place += 2
85
+ elif character == "\n":
86
+ return place
87
+ elif character == "[":
88
+ inside_a_class = True
89
+ place += 1
90
+ elif character == "]":
91
+ inside_a_class = False
92
+ place += 1
93
+ elif character == "/" and not inside_a_class:
94
+ return place + 1
95
+ else:
96
+ place += 1
97
+ return place
98
+
99
+
100
+ def marked_comments(
101
+ text: str,
102
+ quotes: str,
103
+ line_markers: tuple[str, ...],
104
+ block: tuple[str, str],
105
+ patterns: bool,
106
+ ) -> list[int]:
107
+ """Find the comments in a language that marks them with fixed characters.
108
+
109
+ Args:
110
+ text: The file content.
111
+ quotes: Every character that opens a string.
112
+ line_markers: Every marker running a comment to the end of the line.
113
+ block: The opening and closing markers of a block comment.
114
+ patterns: Whether a slash can open a regular expression literal.
115
+
116
+ Returns:
117
+ The lines a comment starts on, sorted and without repeats.
118
+ """
119
+ places: list[int] = []
120
+ place = 0
121
+ while place < len(text):
122
+ character = text[place]
123
+ if character in quotes:
124
+ place = _past_quoted(text, place)
125
+ elif any(text.startswith(marker, place) for marker in line_markers):
126
+ places.append(place)
127
+ place = _past_line(text, place)
128
+ elif text.startswith(block[0], place):
129
+ places.append(place)
130
+ place = _past_block(text, place, block[1])
131
+ elif patterns and character == "/" and _opens_a_pattern(text, place):
132
+ place = _past_pattern(text, place)
133
+ else:
134
+ place += 1
135
+ return _lines_of(text, places)
136
+
137
+
138
+ def hcl_comments(text: str) -> list[int]:
139
+ """Find the comments in an OpenTofu or Terraform file.
140
+
141
+ Args:
142
+ text: The file content.
143
+
144
+ Returns:
145
+ The lines a comment starts on.
146
+ """
147
+ return marked_comments(text, '"', ("#", "//"), ("/*", "*/"), False)
148
+
149
+
150
+ def javascript_comments(text: str) -> list[int]:
151
+ """Find the comments in a JavaScript file.
152
+
153
+ Args:
154
+ text: The file content.
155
+
156
+ Returns:
157
+ The lines a comment starts on.
158
+ """
159
+ return marked_comments(text, "\"'`", ("//",), ("/*", "*/"), True)
160
+
161
+
162
+ def python_comments(text: str) -> list[int]:
163
+ """Find the comments and docstrings in a Python file.
164
+
165
+ A docstring is the first statement of a module, class or function when it
166
+ is a bare string constant, which is prose beside code exactly as a comment
167
+ is.
168
+
169
+ Args:
170
+ text: The file content.
171
+
172
+ Returns:
173
+ The lines a comment or docstring starts on.
174
+ """
175
+ places = [
176
+ token.start[0]
177
+ for token in tokenize.generate_tokens(io.StringIO(text).readline)
178
+ if token.type == tokenize.COMMENT
179
+ ]
180
+ for node in ast.walk(ast.parse(text)):
181
+ if not isinstance(node, DEFINITION_NODES) or not node.body:
182
+ continue
183
+ opening = node.body[0]
184
+ if isinstance(opening, ast.Expr) and isinstance(opening.value, ast.Constant):
185
+ if isinstance(opening.value.value, str):
186
+ places.append(opening.lineno)
187
+ return sorted(set(places))
188
+
189
+
190
+ def yaml_comments(text: str) -> list[int]:
191
+ """Find the comments in a YAML file.
192
+
193
+ The scanner reports the span of every token, so anything left over that is
194
+ not whitespace is a comment.
195
+
196
+ Args:
197
+ text: The file content.
198
+
199
+ Returns:
200
+ The lines a comment starts on.
201
+ """
202
+ covered = bytearray(len(text))
203
+ for token in yaml.scan(text):
204
+ for place in range(token.start_mark.index, token.end_mark.index):
205
+ covered[place] = 1
206
+ return _lines_of(
207
+ text,
208
+ [place for place, seen in enumerate(covered) if not seen and not text[place].isspace()],
209
+ )
210
+
211
+
212
+ GENERATED_FILES = (".terraform.lock.hcl",)
213
+
214
+ READERS: dict[str, Callable[[str], list[int]]] = {
215
+ ".cjs": javascript_comments,
216
+ ".hcl": hcl_comments,
217
+ ".jsx": javascript_comments,
218
+ ".js": javascript_comments,
219
+ ".mjs": javascript_comments,
220
+ ".py": python_comments,
221
+ ".tf": hcl_comments,
222
+ ".tfvars": hcl_comments,
223
+ ".yaml": yaml_comments,
224
+ ".yml": yaml_comments,
225
+ }
226
+
227
+
228
+ def reader_for(path: str) -> Callable[[str], list[int]] | None:
229
+ """Choose the reader for a file, by its suffix.
230
+
231
+ A generated file is nobody's source, so no reader speaks for it either:
232
+ a finding against a lock file is answerable by nobody.
233
+
234
+ Args:
235
+ path: The file path.
236
+
237
+ Returns:
238
+ The reader, or None when no reader speaks for that file.
239
+ """
240
+ if os.path.basename(path) in GENERATED_FILES:
241
+ return None
242
+ return READERS.get(os.path.splitext(path)[1])
243
+
244
+
245
+ def comments_in(path: str, content: str) -> list[Finding]:
246
+ """Find every comment and docstring in one file.
247
+
248
+ Args:
249
+ path: The file path, which chooses the reader.
250
+ content: The file content.
251
+
252
+ Returns:
253
+ A finding for each line carrying a comment, empty when no reader
254
+ speaks the language.
255
+
256
+ Raises:
257
+ Unreadable: The reader could not parse the file.
258
+ """
259
+ reader = reader_for(path)
260
+ if reader is None:
261
+ return []
262
+ try:
263
+ lines = reader(content)
264
+ except (SyntaxError, ValueError, tokenize.TokenError, yaml.YAMLError) as error:
265
+ raise Unreadable(str(error)) from error
266
+ return [Finding(path, line) for line in lines]
@@ -0,0 +1,148 @@
1
+ Metadata-Version: 2.4
2
+ Name: assert-no-comments
3
+ Version: 20260823131905
4
+ Summary: CLI tool to assert that nothing in a tree carries a comment or a docstring
5
+ Author-email: 10U Labs <dev@10ulabs.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/10U-Labs/assert-no-comments
8
+ Project-URL: Repository, https://github.com/10U-Labs/assert-no-comments
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Software Development :: Quality Assurance
19
+ Classifier: Topic :: Software Development :: Testing
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE.txt
23
+ Requires-Dist: pyyaml>=6.0
24
+ Dynamic: license-file
25
+
26
+ # assert-no-comments
27
+
28
+ Assert that nothing in a tree carries a comment or a docstring.
29
+
30
+ ## Why
31
+
32
+ Prose beside code is never checked. The compiler does not read it, the
33
+ tests do not run it, and no linter asks whether it is still true, so it
34
+ stops being true and nothing says when. The reader who believes it then
35
+ works from a program that no longer exists, which is worse than having
36
+ read nothing at all.
37
+
38
+ A rename is where the cost shows up first. Change one identifier and
39
+ every sentence naming it is now wrong, in files the change never
40
+ touched, and the diff gives no way to find them.
41
+
42
+ So this tool takes the other position: a name, a signature and the shape
43
+ of a function are the whole of what a reader gets. When that is not
44
+ enough to say what a thing holds or does, the thing is named or shaped
45
+ wrong rather than under-explained. The reasoning still gets written
46
+ down, in the commit message and the issue, each of which is dated and
47
+ attached to a change instead of sitting beside a line claiming to
48
+ describe it forever.
49
+
50
+ ## Installation
51
+
52
+ ```bash
53
+ pip install assert-no-comments
54
+ ```
55
+
56
+ ## Usage
57
+
58
+ ```bash
59
+ # Every tree this repository publishes
60
+ assert-no-comments .github/workflows etc lib scripts src test
61
+
62
+ # The same, leaving out code somebody else wrote
63
+ assert-no-comments .github/workflows etc lib scripts src test \
64
+ --exclude 'src/www/spa/vendor/*'
65
+ ```
66
+
67
+ ### Options
68
+
69
+ | Option | Effect |
70
+ | --- | --- |
71
+ | `--exclude PATTERNS` | Comma-separated globs to leave out. |
72
+ | `--annotate` | Print each finding as a GitHub Actions `::error` annotation. |
73
+ | `--quiet` | Print nothing; report through the exit code. |
74
+ | `--count` | Print only how many findings there were. |
75
+ | `--verbose` | Print the files read, the findings and a summary. |
76
+ | `--fail-fast` | Stop at the first finding. |
77
+ | `--warn-only` | Always exit 0. |
78
+
79
+ ### Exit codes
80
+
81
+ | Code | Meaning |
82
+ | --- | --- |
83
+ | 0 | Nothing carries a comment |
84
+ | 1 | Something carries a comment |
85
+ | 2 | A tree was missing, unreadable, or would not parse |
86
+
87
+ ## What counts as a comment
88
+
89
+ | Read as | Suffixes | Reported |
90
+ | --- | --- | --- |
91
+ | Python | `.py` | `#`, and any module, class or function docstring |
92
+ | YAML | `.yml`, `.yaml` | `#` |
93
+ | OpenTofu | `.tf`, `.tfvars`, `.hcl` | `#`, `//`, and `/* */` blocks |
94
+ | JavaScript | `.js`, `.jsx`, `.mjs`, `.cjs` | `//`, and `/* */` blocks |
95
+
96
+ A file whose suffix names none of those is left alone, so a `.md` file
97
+ is never read: prose is the content of a markdown file rather than a
98
+ gloss on a line of code. `.terraform.lock.hcl` is left alone too,
99
+ because OpenTofu writes its header and nobody can delete it.
100
+
101
+ A docstring counts as a comment. It is the same prose in the same place,
102
+ and the fact that a language keeps it in `__doc__` does not make it any
103
+ more likely to still be true.
104
+
105
+ Each reader knows the difference between a marker and a character that
106
+ merely looks like one. A `#` inside a Python string, a YAML quoted
107
+ scalar or a block scalar is content. A `//` inside a JavaScript string,
108
+ template literal or regular expression is content, and a `/` after a
109
+ name is division rather than the start of a pattern.
110
+
111
+ Python is read with `tokenize` and `ast`, and YAML with the `yaml`
112
+ scanner, so a file that will not parse is an error rather than a file
113
+ with nothing in it. The marker languages are read character by character
114
+ and never fail: an unclosed string swallows the rest of the file, and an
115
+ unclosed block comment is still reported where it opened.
116
+
117
+ ## What is walked
118
+
119
+ A directory argument is read recursively. Hidden directories are read,
120
+ because `.github/workflows` is one of the trees most worth checking.
121
+ `.git`, `__pycache__` and `node_modules` are skipped, and everything
122
+ else you want left out goes in `--exclude`.
123
+
124
+ The usual thing to exclude is code somebody else wrote:
125
+
126
+ ```bash
127
+ assert-no-comments src --exclude 'src/www/spa/vendor/*'
128
+ ```
129
+
130
+ Nobody here can answer for a vendored library, and a finding against one
131
+ is answerable by nobody, so it is not worth reporting.
132
+
133
+ ## GitHub Actions
134
+
135
+ ```yaml
136
+ - name: Assert nothing this repository publishes carries a comment
137
+ uses: 10U-Labs/assert-no-comments@latest
138
+ with:
139
+ exclude: src/www/spa/vendor/*
140
+ trees: .github/workflows etc lib scripts src test
141
+ ```
142
+
143
+ `annotate` defaults to true there, so each finding lands on the line it
144
+ names in the diff.
145
+
146
+ ## License
147
+
148
+ Apache-2.0
@@ -0,0 +1,11 @@
1
+ assert_no_comments/__init__.py,sha256=a8e_nW-haIHAffTgSdrjpcHv18aQ-WQ1HPp35OSO7vI,70
2
+ assert_no_comments/__main__.py,sha256=G7OM6b3SUaXjKW8bcUMRsWATpGCQa-5DgGnAxDVN64Y,94
3
+ assert_no_comments/cli.py,sha256=kOydsoL1-AP-uTBw6dqqRXMzC5laDbQYU_xA8VQy3Nk,9999
4
+ assert_no_comments/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ assert_no_comments/scanner.py,sha256=g9yxOyd6Kwf-5bJFs8mjdBnaRrxbJKptYXc0Uw3WCPc,7745
6
+ assert_no_comments-20260823131905.dist-info/licenses/LICENSE.txt,sha256=7C7FkuzwSQFE_PL6st5x2YyMN1aiyjZ9ti1s5X45no8,10761
7
+ assert_no_comments-20260823131905.dist-info/METADATA,sha256=HVs4mBD693ctOsPV10WH06eNLB8erzH52oijsWxIzU4,5376
8
+ assert_no_comments-20260823131905.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
9
+ assert_no_comments-20260823131905.dist-info/entry_points.txt,sha256=Wp7TJYwdpIUuX0jmPsXwgN-WabtTdW7AOi9V9bR-4U0,67
10
+ assert_no_comments-20260823131905.dist-info/top_level.txt,sha256=LigOyDP_803WrESxkx0tVyAQKD4zDGHQohSsxVZ_Ke8,19
11
+ assert_no_comments-20260823131905.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ assert-no-comments = assert_no_comments.cli:main
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2024 10U Labs LLC
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
@@ -0,0 +1 @@
1
+ assert_no_comments