apdev 0.1.4__tar.gz → 0.1.6__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: apdev
3
- Version: 0.1.4
3
+ Version: 0.1.6
4
4
  Summary: Shared development tools for Python projects - character validation, circular import detection, and more
5
5
  Author-email: aipartnerup <tercel.yi@gmail.com>
6
6
  License: Apache-2.0
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "apdev"
7
- version = "0.1.4"
7
+ version = "0.1.6"
8
8
  description = "Shared development tools for Python projects - character validation, circular import detection, and more"
9
9
  readme = "README.md"
10
10
  license = {text = "Apache-2.0"}
@@ -1,3 +1,3 @@
1
1
  """apdev - Shared development tools for Python projects."""
2
2
 
3
- __version__ = "0.1.4"
3
+ __version__ = "0.1.6"
@@ -0,0 +1,240 @@
1
+ """Character validation tool.
2
+
3
+ Checks that files contain only allowed characters: ASCII, common emoji,
4
+ and standard technical symbols (arrows, box-drawing, math operators, etc.).
5
+
6
+ Additionally flags dangerous invisible/bidi characters in code regions
7
+ (Trojan Source - CVE-2021-42574) while allowing them in comments.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from pathlib import Path
13
+
14
+ # Allowed Unicode ranges beyond ASCII (0-127)
15
+ EMOJI_RANGES: list[tuple[int, int]] = [
16
+ (0x1F300, 0x1F5FF), # Symbols and Pictographs
17
+ (0x1F600, 0x1F64F), # Emoticons
18
+ (0x1F680, 0x1F6FF), # Transport and Map Symbols
19
+ (0x1F780, 0x1F7FF), # Geometric Shapes Extended
20
+ (0x1F900, 0x1F9FF), # Supplemental Symbols and Pictographs
21
+ (0x2600, 0x26FF), # Miscellaneous Symbols
22
+ (0x2700, 0x27BF), # Dingbats
23
+ ]
24
+
25
+ EXTRA_ALLOWED_RANGES: list[tuple[int, int]] = [
26
+ (0x0080, 0x00FF), # Latin-1 Supplement
27
+ (0x2000, 0x206F), # General Punctuation
28
+ (0x2100, 0x214F), # Letterlike Symbols
29
+ (0x2190, 0x21FF), # Arrows
30
+ (0x2200, 0x22FF), # Mathematical Operators
31
+ (0x2300, 0x23FF), # Miscellaneous Technical
32
+ (0x2500, 0x257F), # Box Drawing
33
+ (0x25A0, 0x25FF), # Geometric Shapes
34
+ (0x2B00, 0x2BFF), # Miscellaneous Symbols and Arrows
35
+ (0xFE00, 0xFE0F), # Variation Selectors
36
+ ]
37
+
38
+ _ALL_RANGES = EMOJI_RANGES + EXTRA_ALLOWED_RANGES
39
+
40
+ # Dangerous codepoints that pass the allowed-range check but should be
41
+ # flagged when they appear in code (not comments). These are within the
42
+ # General Punctuation range (0x2000-0x206F) which is broadly allowed.
43
+ DANGEROUS_CODEPOINTS: dict[int, str] = {
44
+ # Bidi control characters (Trojan Source - CVE-2021-42574)
45
+ 0x202A: "LEFT-TO-RIGHT EMBEDDING",
46
+ 0x202B: "RIGHT-TO-LEFT EMBEDDING",
47
+ 0x202C: "POP DIRECTIONAL FORMATTING",
48
+ 0x202D: "LEFT-TO-RIGHT OVERRIDE",
49
+ 0x202E: "RIGHT-TO-LEFT OVERRIDE",
50
+ 0x2066: "LEFT-TO-RIGHT ISOLATE",
51
+ 0x2067: "RIGHT-TO-LEFT ISOLATE",
52
+ 0x2068: "FIRST STRONG ISOLATE",
53
+ 0x2069: "POP DIRECTIONAL ISOLATE",
54
+ # Zero-width characters
55
+ 0x200B: "ZERO WIDTH SPACE",
56
+ 0x200C: "ZERO WIDTH NON-JOINER",
57
+ 0x200D: "ZERO WIDTH JOINER",
58
+ 0x200E: "LEFT-TO-RIGHT MARK",
59
+ 0x200F: "RIGHT-TO-LEFT MARK",
60
+ 0x2060: "WORD JOINER",
61
+ }
62
+
63
+ _PYTHON_SUFFIXES = {".py"}
64
+ _JS_SUFFIXES = {".js", ".ts", ".tsx", ".jsx", ".mjs", ".cjs"}
65
+
66
+
67
+ def is_allowed_char(c: str) -> bool:
68
+ """Return True if the character is in the allowed set."""
69
+ code = ord(c)
70
+ if code <= 127:
71
+ return True
72
+ for start, end in _ALL_RANGES:
73
+ if start <= code <= end:
74
+ return True
75
+ return False
76
+
77
+
78
+ def is_dangerous_char(c: str) -> bool:
79
+ """Return True if the character is a dangerous invisible/bidi codepoint."""
80
+ return ord(c) in DANGEROUS_CODEPOINTS
81
+
82
+
83
+ def _compute_comment_mask(content: str, suffix: str) -> set[int]:
84
+ """Return the set of character indices that are within comments.
85
+
86
+ Uses a simple state machine that tracks string literals to avoid
87
+ treating ``#`` / ``//`` inside strings as comment starts.
88
+ """
89
+ if suffix in _PYTHON_SUFFIXES:
90
+ return _compute_comment_mask_python(content)
91
+ if suffix in _JS_SUFFIXES:
92
+ return _compute_comment_mask_js(content)
93
+ return set()
94
+
95
+
96
+ def _compute_comment_mask_python(content: str) -> set[int]:
97
+ mask: set[int] = set()
98
+ i = 0
99
+ n = len(content)
100
+
101
+ while i < n:
102
+ # Triple-quoted strings (""" or ''')
103
+ if i + 2 < n and content[i : i + 3] in ('"""', "'''"):
104
+ quote = content[i : i + 3]
105
+ i += 3
106
+ while i < n:
107
+ if content[i] == "\\" and i + 1 < n:
108
+ i += 2
109
+ continue
110
+ if i + 2 < n and content[i : i + 3] == quote:
111
+ i += 3
112
+ break
113
+ i += 1
114
+ continue
115
+
116
+ # Single / double quoted strings
117
+ if content[i] in ('"', "'"):
118
+ quote_char = content[i]
119
+ i += 1
120
+ while i < n and content[i] != "\n":
121
+ if content[i] == "\\" and i + 1 < n:
122
+ i += 2
123
+ continue
124
+ if content[i] == quote_char:
125
+ i += 1
126
+ break
127
+ i += 1
128
+ continue
129
+
130
+ # Line comment
131
+ if content[i] == "#":
132
+ while i < n and content[i] != "\n":
133
+ mask.add(i)
134
+ i += 1
135
+ continue
136
+
137
+ i += 1
138
+
139
+ return mask
140
+
141
+
142
+ def _compute_comment_mask_js(content: str) -> set[int]:
143
+ mask: set[int] = set()
144
+ i = 0
145
+ n = len(content)
146
+
147
+ while i < n:
148
+ # Template literal
149
+ if content[i] == "`":
150
+ i += 1
151
+ while i < n:
152
+ if content[i] == "\\" and i + 1 < n:
153
+ i += 2
154
+ continue
155
+ if content[i] == "`":
156
+ i += 1
157
+ break
158
+ i += 1
159
+ continue
160
+
161
+ # Single / double quoted strings
162
+ if content[i] in ('"', "'"):
163
+ quote_char = content[i]
164
+ i += 1
165
+ while i < n and content[i] != "\n":
166
+ if content[i] == "\\" and i + 1 < n:
167
+ i += 2
168
+ continue
169
+ if content[i] == quote_char:
170
+ i += 1
171
+ break
172
+ i += 1
173
+ continue
174
+
175
+ # Line comment
176
+ if i + 1 < n and content[i : i + 2] == "//":
177
+ while i < n and content[i] != "\n":
178
+ mask.add(i)
179
+ i += 1
180
+ continue
181
+
182
+ # Block comment
183
+ if i + 1 < n and content[i : i + 2] == "/*":
184
+ while i < n:
185
+ if i + 1 < n and content[i : i + 2] == "*/":
186
+ mask.add(i)
187
+ mask.add(i + 1)
188
+ i += 2
189
+ break
190
+ mask.add(i)
191
+ i += 1
192
+ continue
193
+
194
+ i += 1
195
+
196
+ return mask
197
+
198
+
199
+ def check_file(path: Path, *, max_problems: int = 5) -> list[str]:
200
+ """Check a single file for illegal characters.
201
+
202
+ Returns a list of problem descriptions (empty if the file is clean).
203
+ """
204
+ problems: list[str] = []
205
+ try:
206
+ content = path.read_text(encoding="utf-8")
207
+ suffix = path.suffix.lower()
208
+ comment_mask = _compute_comment_mask(content, suffix)
209
+ for i, char in enumerate(content):
210
+ if is_dangerous_char(char):
211
+ if i not in comment_mask:
212
+ code = ord(char)
213
+ name = DANGEROUS_CODEPOINTS[code]
214
+ problems.append(
215
+ f"Dangerous character in code at position {i + 1}: "
216
+ f"U+{code:04X} ({name})"
217
+ )
218
+ elif not is_allowed_char(char):
219
+ problems.append(
220
+ f"Illegal character at position {i + 1}: "
221
+ f"{char!r} (U+{ord(char):04X})"
222
+ )
223
+ if len(problems) >= max_problems:
224
+ break
225
+ except Exception as e:
226
+ problems.append(f"Failed to read file: {e}")
227
+ return problems
228
+
229
+
230
+ def check_paths(paths: list[Path]) -> int:
231
+ """Check multiple files. Returns 0 if all clean, 1 if any have problems."""
232
+ has_error = False
233
+ for path in paths:
234
+ problems = check_file(path)
235
+ if problems:
236
+ has_error = True
237
+ print(f"\n{path} contains illegal characters:")
238
+ for p in problems:
239
+ print(f" {p}")
240
+ return 1 if has_error else 0
@@ -15,15 +15,46 @@ from pathlib import Path
15
15
  class ImportAnalyzer(ast.NodeVisitor):
16
16
  """Collect fully-qualified imports from a single Python file."""
17
17
 
18
- def __init__(self) -> None:
18
+ def __init__(
19
+ self,
20
+ current_module: str = "",
21
+ is_package: bool = False,
22
+ ) -> None:
19
23
  self.imports: set[str] = set()
24
+ self._current_module = current_module
25
+ self._is_package = is_package
20
26
 
21
27
  def visit_Import(self, node: ast.Import) -> None:
22
28
  for alias in node.names:
23
29
  self.imports.add(alias.name)
24
30
 
25
31
  def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
26
- if node.module:
32
+ if node.level > 0 and self._current_module:
33
+ # Relative import – resolve against current module/package.
34
+ parts = self._current_module.split(".")
35
+ # For a package (__init__.py) the package is the module itself;
36
+ # for a regular module the package is the parent.
37
+ if self._is_package:
38
+ levels_to_strip = node.level - 1
39
+ else:
40
+ levels_to_strip = node.level
41
+
42
+ if levels_to_strip > 0 and levels_to_strip < len(parts):
43
+ base_parts = parts[:-levels_to_strip]
44
+ elif levels_to_strip == 0:
45
+ base_parts = list(parts)
46
+ else:
47
+ base_parts = []
48
+
49
+ if node.module:
50
+ resolved = ".".join(base_parts + node.module.split("."))
51
+ self.imports.add(resolved)
52
+ else:
53
+ # ``from . import foo, bar`` – each name is a sub-module.
54
+ for alias in node.names:
55
+ resolved = ".".join(base_parts + [alias.name])
56
+ self.imports.add(resolved)
57
+ elif node.module:
27
58
  self.imports.add(node.module)
28
59
 
29
60
 
@@ -70,7 +101,11 @@ def build_dependency_graph(
70
101
  print(f"Warning: could not parse {py_file}: {e}", file=sys.stderr)
71
102
  continue
72
103
 
73
- analyzer = ImportAnalyzer()
104
+ is_package = py_file.name == "__init__.py"
105
+ analyzer = ImportAnalyzer(
106
+ current_module=module_name,
107
+ is_package=is_package,
108
+ )
74
109
  analyzer.visit(tree)
75
110
 
76
111
  deps = _resolve_imports(analyzer.imports, base_package)
@@ -66,6 +66,11 @@ def _build_parser() -> argparse.ArgumentParser:
66
66
  "release",
67
67
  help="Interactive release automation (build, tag, GitHub release, PyPI upload)",
68
68
  )
69
+ release_parser.add_argument(
70
+ "--yes", "-y",
71
+ action="store_true",
72
+ help="Auto-accept all defaults (silent mode)",
73
+ )
69
74
  release_parser.add_argument(
70
75
  "version",
71
76
  nargs="?",
@@ -108,6 +113,8 @@ def main(argv: list[str] | None = None) -> int:
108
113
  print("Error: release.sh not found in package", file=sys.stderr)
109
114
  return 1
110
115
  cmd = ["bash", str(script)]
116
+ if args.yes:
117
+ cmd.append("--yes")
111
118
  if args.version:
112
119
  cmd.append(args.version)
113
120
  result = subprocess.run(cmd, env={**os.environ})
@@ -1,7 +1,9 @@
1
1
  #!/bin/bash
2
2
  # Interactive release script for Python projects
3
- # Usage: ./release.sh [version]
3
+ # Usage: ./release.sh [--yes|-y] [version]
4
4
  # Example: ./release.sh 0.2.0
5
+ # ./release.sh --yes # silent mode, auto-accept defaults
6
+ # ./release.sh --yes 0.2.0 # silent mode with specific version
5
7
  #
6
8
  # Auto-detects project name from pyproject.toml and GitHub repo from git remote.
7
9
  # Override with environment variables: PROJECT_NAME, PACKAGE_NAME, GITHUB_REPO
@@ -9,6 +11,17 @@
9
11
  # Note: set -e is disabled to allow step-by-step execution
10
12
  # Individual steps will handle their own error handling
11
13
 
14
+ # Silent mode flag (--yes or -y to auto-accept all defaults)
15
+ SILENT=false
16
+ POSITIONAL_ARGS=()
17
+ for arg in "$@"; do
18
+ case "$arg" in
19
+ --yes|-y) SILENT=true ;;
20
+ *) POSITIONAL_ARGS+=("$arg") ;;
21
+ esac
22
+ done
23
+ set -- "${POSITIONAL_ARGS[@]}"
24
+
12
25
  # Colors for output
13
26
  RED='\033[0;31m'
14
27
  GREEN='\033[0;32m'
@@ -56,7 +69,8 @@ else
56
69
  VERSION="$1"
57
70
  fi
58
71
 
59
- TAG="v${VERSION}"
72
+ TAG="python/v${VERSION}"
73
+ TAG_URL_ENCODED="${TAG//\//%2F}"
60
74
 
61
75
  echo -e "${CYAN}╔══════════════════════════════════════════════════════════╗${NC}"
62
76
  echo -e "${CYAN}║ ${PROJECT_NAME} Release Script v${VERSION}${NC}"
@@ -97,13 +111,24 @@ ask_yn() {
97
111
  local prompt="$1"
98
112
  local default="$2"
99
113
  local answer
100
-
114
+
115
+ # Silent mode: auto-accept default
116
+ if [ "$SILENT" = true ]; then
117
+ if [ "$default" = "y" ]; then
118
+ echo -e "${YELLOW}${prompt} [Y/n] y (auto)${NC}"
119
+ return 0
120
+ else
121
+ echo -e "${YELLOW}${prompt} [y/N] n (auto)${NC}"
122
+ return 1
123
+ fi
124
+ fi
125
+
101
126
  if [ "$default" = "y" ]; then
102
127
  prompt="${prompt} [Y/n]"
103
128
  else
104
129
  prompt="${prompt} [y/N]"
105
130
  fi
106
-
131
+
107
132
  read -p "$(echo -e "${YELLOW}${prompt}${NC}") " answer
108
133
  answer=${answer:-$default}
109
134
  [[ $answer =~ ^[Yy]$ ]]
@@ -138,12 +163,19 @@ ask_menu() {
138
163
  # Function to show main menu with all steps
139
164
  # Returns selection via global variable MENU_SELECTION
140
165
  show_main_menu() {
166
+ # Silent mode: auto-select "all"
167
+ if [ "$SILENT" = true ]; then
168
+ echo -e "${CYAN}Silent mode: auto-selecting all steps${NC}"
169
+ MENU_SELECTION="all"
170
+ return
171
+ fi
172
+
141
173
  echo ""
142
174
  echo -e "${CYAN}╔══════════════════════════════════════════════════════════╗${NC}"
143
175
  echo -e "${CYAN}║ Release Steps Selection ║${NC}"
144
176
  echo -e "${CYAN}╚══════════════════════════════════════════════════════════╝${NC}"
145
177
  echo ""
146
-
178
+
147
179
  # Display menu options directly
148
180
  echo -e "${CYAN}Select a step to execute:${NC}"
149
181
  echo -e " ${CYAN}all) Execute all steps (with interactive prompts)${NC}"
@@ -158,7 +190,7 @@ show_main_menu() {
158
190
  echo -e " ${CYAN}9) Show Summary${NC}"
159
191
  echo -e " ${CYAN}0) Exit${NC}"
160
192
  echo ""
161
-
193
+
162
194
  # Read user input directly (not captured)
163
195
  read -p "$(echo -e "${YELLOW}Select option [all]:${NC} ") " MENU_SELECTION
164
196
  MENU_SELECTION=${MENU_SELECTION:-all}
@@ -532,7 +564,7 @@ step6_5_create_github_release() {
532
564
  if [ "$USE_API" = true ] && [ -n "$GITHUB_TOKEN" ]; then
533
565
  # Check via API
534
566
  if curl -s -H "Authorization: token ${GITHUB_TOKEN}" \
535
- "https://api.github.com/repos/${GITHUB_REPO}/releases/tags/${TAG}" \
567
+ "https://api.github.com/repos/${GITHUB_REPO}/releases/tags/${TAG_URL_ENCODED}" \
536
568
  | grep -q '"id"'; then
537
569
  echo -e "${GREEN}✅ Release ${TAG} already exists${NC}"
538
570
  if ask_yn "Update existing release?" "n"; then
@@ -762,19 +794,33 @@ while true; do
762
794
  echo -e "${CYAN}Executing all steps with interactive prompts...${NC}"
763
795
  echo ""
764
796
 
797
+ # Helper: run a step, abort in silent mode on failure
798
+ run_step() {
799
+ local step_name="$1"
800
+ shift
801
+ if ! "$@"; then
802
+ if [ "$SILENT" = true ]; then
803
+ echo -e "${RED}${step_name} failed. Aborting (silent mode).${NC}"
804
+ exit 1
805
+ else
806
+ echo -e "${YELLOW}${step_name} failed, continuing...${NC}"
807
+ fi
808
+ fi
809
+ }
810
+
765
811
  # First verify version (required)
766
812
  if ! step1_version_verification; then
767
813
  echo -e "${RED}Version verification failed. Exiting.${NC}"
768
814
  exit 1
769
815
  fi
770
-
816
+
771
817
  step2_check_status
772
- step3_clean_build || echo -e "${YELLOW}Step 3 failed, continuing...${NC}"
773
- step4_build_package || echo -e "${YELLOW}Step 4 failed, continuing...${NC}"
774
- step5_check_package || echo -e "${YELLOW}Step 5 failed, continuing...${NC}"
775
- step6_git_tag || echo -e "${YELLOW}Step 6 failed, continuing...${NC}"
776
- step6_5_create_github_release || echo -e "${YELLOW}Step 6.5 failed, continuing...${NC}"
777
- step7_upload_pypi || echo -e "${YELLOW}Step 7 failed, continuing...${NC}"
818
+ run_step "Step 3" step3_clean_build
819
+ run_step "Step 4" step4_build_package
820
+ run_step "Step 5" step5_check_package
821
+ run_step "Step 6" step6_git_tag
822
+ run_step "Step 6.5" step6_5_create_github_release
823
+ run_step "Step 7" step7_upload_pypi
778
824
  step_summary
779
825
  break
780
826
  ;;
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: apdev
3
- Version: 0.1.4
3
+ Version: 0.1.6
4
4
  Summary: Shared development tools for Python projects - character validation, circular import detection, and more
5
5
  Author-email: aipartnerup <tercel.yi@gmail.com>
6
6
  License: Apache-2.0
@@ -0,0 +1,196 @@
1
+ """Tests for character validation tool."""
2
+
3
+ from pathlib import Path
4
+
5
+ from apdev.check_chars import (
6
+ check_file,
7
+ check_paths,
8
+ is_allowed_char,
9
+ is_dangerous_char,
10
+ )
11
+
12
+
13
+ def test_ascii_chars_allowed() -> None:
14
+ """All standard ASCII characters (0-127) should be allowed."""
15
+ for i in range(128):
16
+ assert is_allowed_char(chr(i)), f"ASCII {i} should be allowed"
17
+
18
+
19
+ def test_common_emoji_allowed() -> None:
20
+ """Common emoji characters should be allowed."""
21
+ emojis = ["\U0001f600", "\U0001f680", "\u2705", "\u2b50"] # grinning, rocket, check, star
22
+ for emoji in emojis:
23
+ assert is_allowed_char(emoji), f"{emoji!r} should be allowed"
24
+
25
+
26
+ def test_box_drawing_allowed() -> None:
27
+ """Box-drawing characters used in docs should be allowed."""
28
+ chars = ["\u2500", "\u2502", "\u251c", "\u2514"] # horizontal, vertical, tee, corner
29
+ for ch in chars:
30
+ assert is_allowed_char(ch), f"{ch!r} (U+{ord(ch):04X}) should be allowed"
31
+
32
+
33
+ def test_arrow_chars_allowed() -> None:
34
+ """Arrow characters should be allowed."""
35
+ assert is_allowed_char("\u2192") # rightwards arrow
36
+ assert is_allowed_char("\u2190") # leftwards arrow
37
+
38
+
39
+ def test_chinese_chars_rejected() -> None:
40
+ """CJK characters should be rejected by default."""
41
+ assert not is_allowed_char("\u4e2d") # Chinese character
42
+
43
+
44
+ def test_check_file_clean(tmp_path: Path) -> None:
45
+ """File with only ASCII content should pass."""
46
+ f = tmp_path / "clean.py"
47
+ f.write_text("print('hello world')\n", encoding="utf-8")
48
+ problems = check_file(f)
49
+ assert problems == []
50
+
51
+
52
+ def test_check_file_with_illegal_chars(tmp_path: Path) -> None:
53
+ """File with CJK characters should report problems."""
54
+ f = tmp_path / "bad.py"
55
+ f.write_text("x = '\u4e2d\u6587'\n", encoding="utf-8")
56
+ problems = check_file(f)
57
+ assert len(problems) > 0
58
+ assert "U+4E2D" in problems[0]
59
+
60
+
61
+ def test_check_file_max_problems(tmp_path: Path) -> None:
62
+ """Should report at most 5 problems per file."""
63
+ f = tmp_path / "many.py"
64
+ # 10 CJK characters
65
+ f.write_text("\u4e00\u4e01\u4e02\u4e03\u4e04\u4e05\u4e06\u4e07\u4e08\u4e09", encoding="utf-8")
66
+ problems = check_file(f)
67
+ assert len(problems) == 5
68
+
69
+
70
+ def test_check_file_nonexistent(tmp_path: Path) -> None:
71
+ """Non-existent file should report a read error."""
72
+ problems = check_file(tmp_path / "nope.py")
73
+ assert len(problems) == 1
74
+ assert "Failed to read" in problems[0]
75
+
76
+
77
+ def test_check_paths_returns_exit_code(tmp_path: Path) -> None:
78
+ """check_paths returns 0 for clean files, 1 for files with problems."""
79
+ clean = tmp_path / "ok.py"
80
+ clean.write_text("x = 1\n", encoding="utf-8")
81
+ assert check_paths([clean]) == 0
82
+
83
+ bad = tmp_path / "bad.py"
84
+ bad.write_text("x = '\u4e2d'\n", encoding="utf-8")
85
+ assert check_paths([bad]) == 1
86
+
87
+
88
+ # ---------------------------------------------------------------------------
89
+ # Dangerous character tests
90
+ # ---------------------------------------------------------------------------
91
+
92
+ def test_is_dangerous_char() -> None:
93
+ """is_dangerous_char identifies all 15 dangerous codepoints."""
94
+ # Bidi controls
95
+ assert is_dangerous_char("\u202a")
96
+ assert is_dangerous_char("\u202e")
97
+ assert is_dangerous_char("\u2066")
98
+ assert is_dangerous_char("\u2069")
99
+ # Zero-width
100
+ assert is_dangerous_char("\u200b")
101
+ assert is_dangerous_char("\u200d")
102
+ assert is_dangerous_char("\u200e")
103
+ assert is_dangerous_char("\u2060")
104
+ # Normal chars should not be dangerous
105
+ assert not is_dangerous_char("a")
106
+ assert not is_dangerous_char("\u2014") # em dash (General Punctuation, safe)
107
+
108
+
109
+ def test_dangerous_bidi_in_python_code_detected(tmp_path: Path) -> None:
110
+ """Bidi override character in Python code should be flagged."""
111
+ f = tmp_path / "trojan.py"
112
+ # U+202E RIGHT-TO-LEFT OVERRIDE in code
113
+ f.write_text("x = '\u202e'\n", encoding="utf-8")
114
+ problems = check_file(f)
115
+ assert len(problems) == 1
116
+ assert "Dangerous character in code" in problems[0]
117
+ assert "U+202E" in problems[0]
118
+
119
+
120
+ def test_dangerous_bidi_in_python_comment_allowed(tmp_path: Path) -> None:
121
+ """Bidi character inside a Python # comment should be allowed."""
122
+ f = tmp_path / "safe.py"
123
+ f.write_text("x = 1 # test \u202e bidi\n", encoding="utf-8")
124
+ problems = check_file(f)
125
+ assert problems == []
126
+
127
+
128
+ def test_zero_width_in_python_code_detected(tmp_path: Path) -> None:
129
+ """Zero-width space in Python code should be flagged."""
130
+ f = tmp_path / "zw.py"
131
+ f.write_text("x\u200b= 1\n", encoding="utf-8")
132
+ problems = check_file(f)
133
+ assert len(problems) == 1
134
+ assert "ZERO WIDTH SPACE" in problems[0]
135
+
136
+
137
+ def test_dangerous_char_in_python_string_detected(tmp_path: Path) -> None:
138
+ """Dangerous char inside a string literal is still code, not a comment."""
139
+ f = tmp_path / "str.py"
140
+ f.write_text("s = 'hello\u200bworld'\n", encoding="utf-8")
141
+ problems = check_file(f)
142
+ assert len(problems) == 1
143
+ assert "Dangerous character in code" in problems[0]
144
+
145
+
146
+ def test_dangerous_bidi_in_js_line_comment_allowed(tmp_path: Path) -> None:
147
+ """Bidi char inside a JS // comment should be allowed."""
148
+ f = tmp_path / "safe.js"
149
+ f.write_text("let x = 1; // test \u202e bidi\n", encoding="utf-8")
150
+ problems = check_file(f)
151
+ assert problems == []
152
+
153
+
154
+ def test_dangerous_bidi_in_js_block_comment_allowed(tmp_path: Path) -> None:
155
+ """Bidi char inside a JS /* */ comment should be allowed."""
156
+ f = tmp_path / "safe.ts"
157
+ f.write_text("/* \u202e bidi */\nlet x = 1;\n", encoding="utf-8")
158
+ problems = check_file(f)
159
+ assert problems == []
160
+
161
+
162
+ def test_dangerous_bidi_in_js_code_detected(tmp_path: Path) -> None:
163
+ """Bidi char in JS code should be flagged."""
164
+ f = tmp_path / "trojan.ts"
165
+ f.write_text("let x = '\u202e';\n", encoding="utf-8")
166
+ problems = check_file(f)
167
+ assert len(problems) == 1
168
+ assert "Dangerous character in code" in problems[0]
169
+
170
+
171
+ def test_cjk_still_rejected_after_dangerous_check(tmp_path: Path) -> None:
172
+ """CJK characters should still be caught as illegal (not dangerous)."""
173
+ f = tmp_path / "cjk.py"
174
+ f.write_text("x = '\u4e2d'\n", encoding="utf-8")
175
+ problems = check_file(f)
176
+ assert len(problems) == 1
177
+ assert "Illegal character" in problems[0]
178
+
179
+
180
+ def test_hash_in_python_string_not_treated_as_comment(tmp_path: Path) -> None:
181
+ """# inside a string should not start a comment region."""
182
+ f = tmp_path / "hash_str.py"
183
+ # The \u202e is after the string, in code – should be flagged
184
+ f.write_text("s = '# not a comment'\u202e\n", encoding="utf-8")
185
+ problems = check_file(f)
186
+ assert len(problems) == 1
187
+ assert "Dangerous character in code" in problems[0]
188
+
189
+
190
+ def test_unknown_extension_treats_all_as_code(tmp_path: Path) -> None:
191
+ """For unknown extensions, all chars are treated as code (conservative)."""
192
+ f = tmp_path / "file.txt"
193
+ f.write_text("hello \u202e world\n", encoding="utf-8")
194
+ problems = check_file(f)
195
+ assert len(problems) == 1
196
+ assert "Dangerous character in code" in problems[0]
@@ -0,0 +1,181 @@
1
+ """Tests for circular import detection tool."""
2
+
3
+ import ast
4
+ from pathlib import Path
5
+
6
+ from apdev.check_imports import (
7
+ ImportAnalyzer,
8
+ build_dependency_graph,
9
+ file_to_module,
10
+ find_cycles,
11
+ )
12
+
13
+
14
+ def test_file_to_module_regular(tmp_path: Path) -> None:
15
+ """Regular .py file converts to dotted module name."""
16
+ f = tmp_path / "pkg" / "sub" / "mod.py"
17
+ assert file_to_module(f, tmp_path) == "pkg.sub.mod"
18
+
19
+
20
+ def test_file_to_module_init(tmp_path: Path) -> None:
21
+ """__init__.py converts to package name without __init__."""
22
+ f = tmp_path / "pkg" / "__init__.py"
23
+ assert file_to_module(f, tmp_path) == "pkg"
24
+
25
+
26
+ def test_import_analyzer_import() -> None:
27
+ """ImportAnalyzer collects 'import x' statements."""
28
+ source = "import os\nimport pkg.sub"
29
+ tree = ast.parse(source)
30
+ analyzer = ImportAnalyzer()
31
+ analyzer.visit(tree)
32
+ assert "os" in analyzer.imports
33
+ assert "pkg.sub" in analyzer.imports
34
+
35
+
36
+ def test_import_analyzer_from_import() -> None:
37
+ """ImportAnalyzer collects 'from x import y' statements."""
38
+ source = "from pkg.sub import something"
39
+ tree = ast.parse(source)
40
+ analyzer = ImportAnalyzer()
41
+ analyzer.visit(tree)
42
+ assert "pkg.sub" in analyzer.imports
43
+
44
+
45
+ def test_build_graph_no_cycles(tmp_path: Path) -> None:
46
+ """Build graph for a package with no circular imports."""
47
+ src = tmp_path / "mypkg"
48
+ src.mkdir()
49
+ (src / "__init__.py").write_text("")
50
+ (src / "a.py").write_text("from mypkg.b import something\n")
51
+ (src / "b.py").write_text("import os\n")
52
+
53
+ graph = build_dependency_graph(tmp_path, base_package="mypkg")
54
+ assert "mypkg.b" in graph.get("mypkg.a", set())
55
+ assert graph.get("mypkg.b", set()) == set()
56
+
57
+
58
+ def test_build_graph_with_cycle(tmp_path: Path) -> None:
59
+ """Build graph for a package with circular imports."""
60
+ src = tmp_path / "mypkg"
61
+ src.mkdir()
62
+ (src / "__init__.py").write_text("")
63
+ (src / "a.py").write_text("from mypkg.b import something\n")
64
+ (src / "b.py").write_text("from mypkg.a import something\n")
65
+
66
+ graph = build_dependency_graph(tmp_path, base_package="mypkg")
67
+ cycles = find_cycles(graph)
68
+ assert len(cycles) == 1
69
+ cycle_modules = set(cycles[0][:-1])
70
+ assert cycle_modules == {"mypkg.a", "mypkg.b"}
71
+
72
+
73
+ def test_find_cycles_no_cycle() -> None:
74
+ """No cycles in a DAG."""
75
+ graph = {"a": {"b"}, "b": {"c"}, "c": set()}
76
+ assert find_cycles(graph) == []
77
+
78
+
79
+ def test_find_cycles_self_loop() -> None:
80
+ """Detect a self-referencing module (edge case)."""
81
+ graph = {"a": {"a"}}
82
+ cycles = find_cycles(graph)
83
+ assert len(cycles) == 1
84
+
85
+
86
+ def test_find_cycles_deduplication() -> None:
87
+ """Cycles are deduplicated regardless of starting node."""
88
+ graph = {"a": {"b"}, "b": {"c"}, "c": {"a"}}
89
+ cycles = find_cycles(graph)
90
+ assert len(cycles) == 1
91
+
92
+
93
+ # ---------------------------------------------------------------------------
94
+ # Relative import tests
95
+ # ---------------------------------------------------------------------------
96
+
97
+ def test_import_analyzer_relative_from_dot_module() -> None:
98
+ """'from .b import x' in mypkg.a resolves to mypkg.b."""
99
+ source = "from .b import something"
100
+ tree = ast.parse(source)
101
+ analyzer = ImportAnalyzer(current_module="mypkg.a", is_package=False)
102
+ analyzer.visit(tree)
103
+ assert "mypkg.b" in analyzer.imports
104
+
105
+
106
+ def test_import_analyzer_relative_from_dot_import() -> None:
107
+ """'from . import b' in mypkg.a resolves to mypkg.b."""
108
+ source = "from . import b"
109
+ tree = ast.parse(source)
110
+ analyzer = ImportAnalyzer(current_module="mypkg.a", is_package=False)
111
+ analyzer.visit(tree)
112
+ assert "mypkg.b" in analyzer.imports
113
+
114
+
115
+ def test_import_analyzer_relative_dotdot() -> None:
116
+ """'from ..c import x' in mypkg.sub.a resolves to mypkg.c."""
117
+ source = "from ..c import something"
118
+ tree = ast.parse(source)
119
+ analyzer = ImportAnalyzer(current_module="mypkg.sub.a", is_package=False)
120
+ analyzer.visit(tree)
121
+ assert "mypkg.c" in analyzer.imports
122
+
123
+
124
+ def test_import_analyzer_relative_in_package() -> None:
125
+ """'from .b import x' in mypkg.__init__ (package) resolves to mypkg.b."""
126
+ source = "from .b import something"
127
+ tree = ast.parse(source)
128
+ analyzer = ImportAnalyzer(current_module="mypkg", is_package=True)
129
+ analyzer.visit(tree)
130
+ assert "mypkg.b" in analyzer.imports
131
+
132
+
133
+ def test_build_graph_relative_import_cycle(tmp_path: Path) -> None:
134
+ """Relative imports should be detected and form cycles."""
135
+ src = tmp_path / "mypkg"
136
+ src.mkdir()
137
+ (src / "__init__.py").write_text("")
138
+ (src / "a.py").write_text("from .b import something\n")
139
+ (src / "b.py").write_text("from .a import something\n")
140
+
141
+ graph = build_dependency_graph(tmp_path, base_package="mypkg")
142
+ assert "mypkg.b" in graph.get("mypkg.a", set())
143
+ assert "mypkg.a" in graph.get("mypkg.b", set())
144
+
145
+ cycles = find_cycles(graph)
146
+ assert len(cycles) == 1
147
+ cycle_modules = set(cycles[0][:-1])
148
+ assert cycle_modules == {"mypkg.a", "mypkg.b"}
149
+
150
+
151
+ def test_build_graph_relative_no_cycle(tmp_path: Path) -> None:
152
+ """Relative imports without a cycle should not report cycles."""
153
+ src = tmp_path / "mypkg"
154
+ src.mkdir()
155
+ (src / "__init__.py").write_text("")
156
+ (src / "a.py").write_text("from .b import something\n")
157
+ (src / "b.py").write_text("import os\n")
158
+
159
+ graph = build_dependency_graph(tmp_path, base_package="mypkg")
160
+ assert "mypkg.b" in graph.get("mypkg.a", set())
161
+ cycles = find_cycles(graph)
162
+ assert cycles == []
163
+
164
+
165
+ def test_build_graph_relative_from_subpackage(tmp_path: Path) -> None:
166
+ """Relative imports in a sub-package resolve correctly."""
167
+ pkg = tmp_path / "mypkg"
168
+ pkg.mkdir()
169
+ (pkg / "__init__.py").write_text("")
170
+ sub = pkg / "sub"
171
+ sub.mkdir()
172
+ (sub / "__init__.py").write_text("")
173
+ (sub / "a.py").write_text("from .b import something\n")
174
+ (sub / "b.py").write_text("from .a import something\n")
175
+
176
+ graph = build_dependency_graph(tmp_path, base_package="mypkg")
177
+ assert "mypkg.sub.b" in graph.get("mypkg.sub.a", set())
178
+ assert "mypkg.sub.a" in graph.get("mypkg.sub.b", set())
179
+
180
+ cycles = find_cycles(graph)
181
+ assert len(cycles) == 1
@@ -1,79 +0,0 @@
1
- """Character validation tool.
2
-
3
- Checks that files contain only allowed characters: ASCII, common emoji,
4
- and standard technical symbols (arrows, box-drawing, math operators, etc.).
5
- """
6
-
7
- from __future__ import annotations
8
-
9
- from pathlib import Path
10
-
11
- # Allowed Unicode ranges beyond ASCII (0-127)
12
- EMOJI_RANGES: list[tuple[int, int]] = [
13
- (0x1F300, 0x1F5FF), # Symbols and Pictographs
14
- (0x1F600, 0x1F64F), # Emoticons
15
- (0x1F680, 0x1F6FF), # Transport and Map Symbols
16
- (0x1F780, 0x1F7FF), # Geometric Shapes Extended
17
- (0x1F900, 0x1F9FF), # Supplemental Symbols and Pictographs
18
- (0x2600, 0x26FF), # Miscellaneous Symbols
19
- (0x2700, 0x27BF), # Dingbats
20
- ]
21
-
22
- EXTRA_ALLOWED_RANGES: list[tuple[int, int]] = [
23
- (0x0080, 0x00FF), # Latin-1 Supplement
24
- (0x2000, 0x206F), # General Punctuation
25
- (0x2100, 0x214F), # Letterlike Symbols
26
- (0x2190, 0x21FF), # Arrows
27
- (0x2200, 0x22FF), # Mathematical Operators
28
- (0x2300, 0x23FF), # Miscellaneous Technical
29
- (0x2500, 0x257F), # Box Drawing
30
- (0x25A0, 0x25FF), # Geometric Shapes
31
- (0x2B00, 0x2BFF), # Miscellaneous Symbols and Arrows
32
- (0xFE00, 0xFE0F), # Variation Selectors
33
- ]
34
-
35
- _ALL_RANGES = EMOJI_RANGES + EXTRA_ALLOWED_RANGES
36
-
37
-
38
- def is_allowed_char(c: str) -> bool:
39
- """Return True if the character is in the allowed set."""
40
- code = ord(c)
41
- if code <= 127:
42
- return True
43
- for start, end in _ALL_RANGES:
44
- if start <= code <= end:
45
- return True
46
- return False
47
-
48
-
49
- def check_file(path: Path, *, max_problems: int = 5) -> list[str]:
50
- """Check a single file for illegal characters.
51
-
52
- Returns a list of problem descriptions (empty if the file is clean).
53
- """
54
- problems: list[str] = []
55
- try:
56
- content = path.read_text(encoding="utf-8")
57
- for i, char in enumerate(content, 1):
58
- if not is_allowed_char(char):
59
- problems.append(
60
- f"Illegal character at position {i}: {char!r} (U+{ord(char):04X})"
61
- )
62
- if len(problems) >= max_problems:
63
- break
64
- except Exception as e:
65
- problems.append(f"Failed to read file: {e}")
66
- return problems
67
-
68
-
69
- def check_paths(paths: list[Path]) -> int:
70
- """Check multiple files. Returns 0 if all clean, 1 if any have problems."""
71
- has_error = False
72
- for path in paths:
73
- problems = check_file(path)
74
- if problems:
75
- has_error = True
76
- print(f"\n{path} contains illegal characters:")
77
- for p in problems:
78
- print(f" {p}")
79
- return 1 if has_error else 0
@@ -1,80 +0,0 @@
1
- """Tests for character validation tool."""
2
-
3
- from pathlib import Path
4
-
5
- from apdev.check_chars import check_file, check_paths, is_allowed_char
6
-
7
-
8
- def test_ascii_chars_allowed() -> None:
9
- """All standard ASCII characters (0-127) should be allowed."""
10
- for i in range(128):
11
- assert is_allowed_char(chr(i)), f"ASCII {i} should be allowed"
12
-
13
-
14
- def test_common_emoji_allowed() -> None:
15
- """Common emoji characters should be allowed."""
16
- emojis = ["\U0001f600", "\U0001f680", "\u2705", "\u2b50"] # grinning, rocket, check, star
17
- for emoji in emojis:
18
- assert is_allowed_char(emoji), f"{emoji!r} should be allowed"
19
-
20
-
21
- def test_box_drawing_allowed() -> None:
22
- """Box-drawing characters used in docs should be allowed."""
23
- chars = ["\u2500", "\u2502", "\u251c", "\u2514"] # horizontal, vertical, tee, corner
24
- for ch in chars:
25
- assert is_allowed_char(ch), f"{ch!r} (U+{ord(ch):04X}) should be allowed"
26
-
27
-
28
- def test_arrow_chars_allowed() -> None:
29
- """Arrow characters should be allowed."""
30
- assert is_allowed_char("\u2192") # rightwards arrow
31
- assert is_allowed_char("\u2190") # leftwards arrow
32
-
33
-
34
- def test_chinese_chars_rejected() -> None:
35
- """CJK characters should be rejected by default."""
36
- assert not is_allowed_char("\u4e2d") # Chinese character
37
-
38
-
39
- def test_check_file_clean(tmp_path: Path) -> None:
40
- """File with only ASCII content should pass."""
41
- f = tmp_path / "clean.py"
42
- f.write_text("print('hello world')\n", encoding="utf-8")
43
- problems = check_file(f)
44
- assert problems == []
45
-
46
-
47
- def test_check_file_with_illegal_chars(tmp_path: Path) -> None:
48
- """File with CJK characters should report problems."""
49
- f = tmp_path / "bad.py"
50
- f.write_text("x = '\u4e2d\u6587'\n", encoding="utf-8")
51
- problems = check_file(f)
52
- assert len(problems) > 0
53
- assert "U+4E2D" in problems[0]
54
-
55
-
56
- def test_check_file_max_problems(tmp_path: Path) -> None:
57
- """Should report at most 5 problems per file."""
58
- f = tmp_path / "many.py"
59
- # 10 CJK characters
60
- f.write_text("\u4e00\u4e01\u4e02\u4e03\u4e04\u4e05\u4e06\u4e07\u4e08\u4e09", encoding="utf-8")
61
- problems = check_file(f)
62
- assert len(problems) == 5
63
-
64
-
65
- def test_check_file_nonexistent(tmp_path: Path) -> None:
66
- """Non-existent file should report a read error."""
67
- problems = check_file(tmp_path / "nope.py")
68
- assert len(problems) == 1
69
- assert "Failed to read" in problems[0]
70
-
71
-
72
- def test_check_paths_returns_exit_code(tmp_path: Path) -> None:
73
- """check_paths returns 0 for clean files, 1 for files with problems."""
74
- clean = tmp_path / "ok.py"
75
- clean.write_text("x = 1\n", encoding="utf-8")
76
- assert check_paths([clean]) == 0
77
-
78
- bad = tmp_path / "bad.py"
79
- bad.write_text("x = '\u4e2d'\n", encoding="utf-8")
80
- assert check_paths([bad]) == 1
@@ -1,103 +0,0 @@
1
- """Tests for circular import detection tool."""
2
-
3
- import textwrap
4
- from pathlib import Path
5
-
6
- from apdev.check_imports import (
7
- ImportAnalyzer,
8
- build_dependency_graph,
9
- file_to_module,
10
- find_cycles,
11
- )
12
-
13
-
14
- def _write_module(base: Path, dotted_name: str, content: str) -> Path:
15
- """Helper: create a Python module file under base/src_dir structure."""
16
- parts = dotted_name.split(".")
17
- file_path = base.joinpath(*parts[:-1], parts[-1] + ".py")
18
- file_path.parent.mkdir(parents=True, exist_ok=True)
19
- file_path.write_text(textwrap.dedent(content))
20
- return file_path
21
-
22
-
23
- def test_file_to_module_regular(tmp_path: Path) -> None:
24
- """Regular .py file converts to dotted module name."""
25
- f = tmp_path / "pkg" / "sub" / "mod.py"
26
- assert file_to_module(f, tmp_path) == "pkg.sub.mod"
27
-
28
-
29
- def test_file_to_module_init(tmp_path: Path) -> None:
30
- """__init__.py converts to package name without __init__."""
31
- f = tmp_path / "pkg" / "__init__.py"
32
- assert file_to_module(f, tmp_path) == "pkg"
33
-
34
-
35
- def test_import_analyzer_import() -> None:
36
- """ImportAnalyzer collects 'import x' statements."""
37
- import ast
38
-
39
- source = "import os\nimport pkg.sub"
40
- tree = ast.parse(source)
41
- analyzer = ImportAnalyzer()
42
- analyzer.visit(tree)
43
- assert "os" in analyzer.imports
44
- assert "pkg.sub" in analyzer.imports
45
-
46
-
47
- def test_import_analyzer_from_import() -> None:
48
- """ImportAnalyzer collects 'from x import y' statements."""
49
- import ast
50
-
51
- source = "from pkg.sub import something"
52
- tree = ast.parse(source)
53
- analyzer = ImportAnalyzer()
54
- analyzer.visit(tree)
55
- assert "pkg.sub" in analyzer.imports
56
-
57
-
58
- def test_build_graph_no_cycles(tmp_path: Path) -> None:
59
- """Build graph for a package with no circular imports."""
60
- src = tmp_path / "mypkg"
61
- src.mkdir()
62
- (src / "__init__.py").write_text("")
63
- (src / "a.py").write_text("from mypkg.b import something\n")
64
- (src / "b.py").write_text("import os\n")
65
-
66
- graph = build_dependency_graph(tmp_path, base_package="mypkg")
67
- assert "mypkg.b" in graph.get("mypkg.a", set())
68
- assert graph.get("mypkg.b", set()) == set()
69
-
70
-
71
- def test_build_graph_with_cycle(tmp_path: Path) -> None:
72
- """Build graph for a package with circular imports."""
73
- src = tmp_path / "mypkg"
74
- src.mkdir()
75
- (src / "__init__.py").write_text("")
76
- (src / "a.py").write_text("from mypkg.b import something\n")
77
- (src / "b.py").write_text("from mypkg.a import something\n")
78
-
79
- graph = build_dependency_graph(tmp_path, base_package="mypkg")
80
- cycles = find_cycles(graph)
81
- assert len(cycles) == 1
82
- cycle_modules = set(cycles[0][:-1])
83
- assert cycle_modules == {"mypkg.a", "mypkg.b"}
84
-
85
-
86
- def test_find_cycles_no_cycle() -> None:
87
- """No cycles in a DAG."""
88
- graph = {"a": {"b"}, "b": {"c"}, "c": set()}
89
- assert find_cycles(graph) == []
90
-
91
-
92
- def test_find_cycles_self_loop() -> None:
93
- """Detect a self-referencing module (edge case)."""
94
- graph = {"a": {"a"}}
95
- cycles = find_cycles(graph)
96
- assert len(cycles) == 1
97
-
98
-
99
- def test_find_cycles_deduplication() -> None:
100
- """Cycles are deduplicated regardless of starting node."""
101
- graph = {"a": {"b"}, "b": {"c"}, "c": {"a"}}
102
- cycles = find_cycles(graph)
103
- assert len(cycles) == 1
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes