py2max 0.5.1__tar.gz → 0.7.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. {py2max-0.5.1 → py2max-0.7.0}/CHANGELOG.md +178 -1
  2. {py2max-0.5.1 → py2max-0.7.0}/PKG-INFO +6 -3
  3. {py2max-0.5.1 → py2max-0.7.0}/README.md +4 -2
  4. {py2max-0.5.1 → py2max-0.7.0}/py2max/__init__.py +3 -2
  5. py2max-0.7.0/py2max/check.py +251 -0
  6. {py2max-0.5.1 → py2max-0.7.0}/py2max/cli.py +140 -34
  7. {py2max-0.5.1 → py2max-0.7.0}/py2max/core/abstract.py +14 -5
  8. {py2max-0.5.1 → py2max-0.7.0}/py2max/core/box.py +50 -8
  9. {py2max-0.5.1 → py2max-0.7.0}/py2max/core/factory.py +244 -73
  10. {py2max-0.5.1 → py2max-0.7.0}/py2max/core/patcher.py +154 -48
  11. {py2max-0.5.1 → py2max-0.7.0}/py2max/core/patchline.py +2 -1
  12. {py2max-0.5.1 → py2max-0.7.0}/py2max/core/props.py +4 -2
  13. {py2max-0.5.1 → py2max-0.7.0}/py2max/core/serialization.py +5 -2
  14. {py2max-0.5.1 → py2max-0.7.0}/py2max/data/js2max/js2max.js +1 -1
  15. {py2max-0.5.1 → py2max-0.7.0}/py2max/data/js2max/js2max.v8.js +1 -1
  16. {py2max-0.5.1 → py2max-0.7.0}/py2max/exceptions.py +6 -2
  17. {py2max-0.5.1 → py2max-0.7.0}/py2max/export/converters.py +34 -12
  18. {py2max-0.5.1 → py2max-0.7.0}/py2max/export/svg.py +12 -8
  19. {py2max-0.5.1 → py2max-0.7.0}/py2max/layout/__init__.py +8 -1
  20. {py2max-0.5.1 → py2max-0.7.0}/py2max/layout/base.py +141 -56
  21. {py2max-0.5.1 → py2max-0.7.0}/py2max/layout/external.py +6 -1
  22. {py2max-0.5.1 → py2max-0.7.0}/py2max/layout/flow.py +19 -15
  23. {py2max-0.5.1 → py2max-0.7.0}/py2max/layout/graph.py +0 -35
  24. {py2max-0.5.1 → py2max-0.7.0}/py2max/layout/grid.py +17 -17
  25. {py2max-0.5.1 → py2max-0.7.0}/py2max/layout/matrix.py +12 -9
  26. py2max-0.7.0/py2max/lint.py +445 -0
  27. {py2max-0.5.1 → py2max-0.7.0}/py2max/log.py +13 -5
  28. {py2max-0.5.1 → py2max-0.7.0}/py2max/m4l.py +75 -34
  29. {py2max-0.5.1 → py2max-0.7.0}/py2max/maxref/category.py +0 -9
  30. {py2max-0.5.1 → py2max-0.7.0}/py2max/maxref/db.py +75 -20
  31. {py2max-0.5.1 → py2max-0.7.0}/py2max/maxref/legacy.py +2 -2
  32. {py2max-0.5.1 → py2max-0.7.0}/py2max/maxref/parser.py +60 -18
  33. {py2max-0.5.1 → py2max-0.7.0}/py2max/maxref/porttypes.py +1 -1
  34. {py2max-0.5.1 → py2max-0.7.0}/py2max/transformers.py +2 -2
  35. {py2max-0.5.1 → py2max-0.7.0}/py2max/utils.py +27 -3
  36. {py2max-0.5.1 → py2max-0.7.0}/pyproject.toml +14 -2
  37. {py2max-0.5.1 → py2max-0.7.0}/pyproject.toml.orig +17 -2
  38. {py2max-0.5.1 → py2max-0.7.0}/tests/conftest.py +0 -102
  39. py2max-0.7.0/tests/examples/advanced/connection_patterns.py +175 -0
  40. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/advanced/custom_extensions.py +63 -31
  41. py2max-0.7.0/tests/examples/advanced/data_containers.py +178 -0
  42. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/advanced/error_handling.py +2 -1
  43. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/advanced/performance_optimization.py +34 -21
  44. py2max-0.7.0/tests/examples/advanced/subpatchers.py +102 -0
  45. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/api/box_api_examples.py +19 -12
  46. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/api/patcher_api_examples.py +25 -17
  47. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/auto_layout_demo.py +37 -28
  48. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/layout/columnar_layout_examples.py +18 -7
  49. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/layout/flow_layout_examples.py +49 -29
  50. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/layout/grid_layout_examples.py +53 -19
  51. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/layout/matrix_layout_examples.py +54 -47
  52. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/preview/basic_synth.maxpat +13 -17
  53. py2max-0.7.0/tests/examples/preview/basic_synth.svg +42 -0
  54. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/preview/complex_synth.maxpat +169 -81
  55. py2max-0.7.0/tests/examples/preview/complex_synth.svg +99 -0
  56. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/preview/flow_layout.maxpat +39 -30
  57. py2max-0.7.0/tests/examples/preview/flow_layout.svg +49 -0
  58. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/preview/grid_layout.maxpat +29 -20
  59. py2max-0.7.0/tests/examples/preview/grid_layout.svg +49 -0
  60. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/preview/horizontal_layout.maxpat +29 -20
  61. py2max-0.7.0/tests/examples/preview/horizontal_layout.svg +49 -0
  62. py2max-0.7.0/tests/examples/preview/styled_no_ports.svg +28 -0
  63. py2max-0.7.0/tests/examples/preview/styled_no_title.svg +31 -0
  64. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/preview/styled_patch.maxpat +25 -13
  65. py2max-0.7.0/tests/examples/preview/styled_with_ports.svg +33 -0
  66. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/preview/svg_preview_demo.py +20 -12
  67. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/preview/vertical_layout.maxpat +29 -20
  68. py2max-0.7.0/tests/examples/preview/vertical_layout.svg +49 -0
  69. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/preview/workflow_demo.maxpat +16 -20
  70. py2max-0.7.0/tests/examples/preview/workflow_demo.svg +52 -0
  71. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/quickstart/basic_patch.py +2 -1
  72. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/quickstart/layout_examples.py +12 -4
  73. py2max-0.7.0/tests/examples/tutorial/generative_music.py +118 -0
  74. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/tutorial/interactive_controller.py +2 -1
  75. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/tutorial/signal_processing_chain.py +29 -18
  76. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/tutorial/simple_synthesis.py +1 -0
  77. {py2max-0.5.1 → py2max-0.7.0}/tests/test_abstract_coverage.py +0 -27
  78. {py2max-0.5.1 → py2max-0.7.0}/tests/test_add.py +50 -0
  79. {py2max-0.5.1 → py2max-0.7.0}/tests/test_amxd.py +58 -0
  80. {py2max-0.5.1 → py2max-0.7.0}/tests/test_attrui.py +1 -1
  81. py2max-0.7.0/tests/test_auto_layout.py +130 -0
  82. {py2max-0.5.1 → py2max-0.7.0}/tests/test_cli.py +117 -0
  83. {py2max-0.5.1 → py2max-0.7.0}/tests/test_converters.py +81 -0
  84. {py2max-0.5.1 → py2max-0.7.0}/tests/test_core_coverage.py +11 -7
  85. {py2max-0.5.1 → py2max-0.7.0}/tests/test_db.py +31 -0
  86. py2max-0.7.0/tests/test_dict.py +51 -0
  87. {py2max-0.5.1 → py2max-0.7.0}/tests/test_encapsulate.py +14 -14
  88. {py2max-0.5.1 → py2max-0.7.0}/tests/test_examples.py +77 -12
  89. {py2max-0.5.1 → py2max-0.7.0}/tests/test_itable.py +1 -1
  90. py2max-0.7.0/tests/test_layout_align_ports.py +148 -0
  91. {py2max-0.5.1 → py2max-0.7.0}/tests/test_layout_flow.py +17 -0
  92. {py2max-0.5.1 → py2max-0.7.0}/tests/test_layout_graph.py +0 -16
  93. {py2max-0.5.1 → py2max-0.7.0}/tests/test_layout_graph_manager.py +38 -4
  94. {py2max-0.5.1 → py2max-0.7.0}/tests/test_layout_matrix.py +2 -2
  95. py2max-0.7.0/tests/test_layout_placement.py +330 -0
  96. {py2max-0.5.1 → py2max-0.7.0}/tests/test_layout_subset.py +14 -7
  97. {py2max-0.5.1 → py2max-0.7.0}/tests/test_lint.py +38 -0
  98. py2max-0.7.0/tests/test_load_save_fidelity.py +146 -0
  99. {py2max-0.5.1 → py2max-0.7.0}/tests/test_loaded_rects.py +29 -0
  100. {py2max-0.5.1 → py2max-0.7.0}/tests/test_logging.py +15 -0
  101. {py2max-0.5.1 → py2max-0.7.0}/tests/test_maxref.py +11 -0
  102. {py2max-0.5.1 → py2max-0.7.0}/tests/test_maxref_refpages.py +64 -0
  103. {py2max-0.5.1 → py2max-0.7.0}/tests/test_on_invalid.py +44 -0
  104. {py2max-0.5.1 → py2max-0.7.0}/tests/test_patcher.py +1 -1
  105. {py2max-0.5.1 → py2max-0.7.0}/tests/test_semantic_ids.py +30 -1
  106. {py2max-0.5.1 → py2max-0.7.0}/tests/test_subpatch.py +56 -0
  107. {py2max-0.5.1 → py2max-0.7.0}/tests/test_svg.py +8 -8
  108. {py2max-0.5.1 → py2max-0.7.0}/tests/test_table.py +38 -10
  109. {py2max-0.5.1 → py2max-0.7.0}/tests/test_utils.py +7 -0
  110. py2max-0.7.0/tests/test_validate.py +284 -0
  111. {py2max-0.5.1 → py2max-0.7.0}/tests/test_validate_attrs.py +21 -0
  112. py2max-0.7.0/tests/test_version.py +13 -0
  113. py2max-0.5.1/py2max/lint.py +0 -238
  114. py2max-0.5.1/tests/examples/advanced/connection_patterns.py +0 -128
  115. py2max-0.5.1/tests/examples/advanced/data_containers.py +0 -141
  116. py2max-0.5.1/tests/examples/advanced/subpatchers.py +0 -90
  117. py2max-0.5.1/tests/examples/preview/basic_synth.svg +0 -39
  118. py2max-0.5.1/tests/examples/preview/complex_synth.svg +0 -71
  119. py2max-0.5.1/tests/examples/preview/flow_layout.svg +0 -45
  120. py2max-0.5.1/tests/examples/preview/grid_layout.svg +0 -45
  121. py2max-0.5.1/tests/examples/preview/horizontal_layout.svg +0 -45
  122. py2max-0.5.1/tests/examples/preview/styled_no_ports.svg +0 -22
  123. py2max-0.5.1/tests/examples/preview/styled_no_title.svg +0 -27
  124. py2max-0.5.1/tests/examples/preview/styled_with_ports.svg +0 -29
  125. py2max-0.5.1/tests/examples/preview/vertical_layout.svg +0 -45
  126. py2max-0.5.1/tests/examples/preview/workflow_demo.svg +0 -50
  127. py2max-0.5.1/tests/examples/tutorial/generative_music.py +0 -104
  128. py2max-0.5.1/tests/test_dict.py +0 -15
  129. {py2max-0.5.1 → py2max-0.7.0}/LICENSE +0 -0
  130. {py2max-0.5.1 → py2max-0.7.0}/py2max/__main__.py +0 -0
  131. {py2max-0.5.1 → py2max-0.7.0}/py2max/core/__init__.py +0 -0
  132. {py2max-0.5.1 → py2max-0.7.0}/py2max/core/colors.py +0 -0
  133. {py2max-0.5.1 → py2max-0.7.0}/py2max/core/common.py +0 -0
  134. {py2max-0.5.1 → py2max-0.7.0}/py2max/export/__init__.py +0 -0
  135. {py2max-0.5.1 → py2max-0.7.0}/py2max/js2max_runtime.py +0 -0
  136. {py2max-0.5.1 → py2max-0.7.0}/py2max/maxref/__init__.py +0 -0
  137. {py2max-0.5.1 → py2max-0.7.0}/py2max/maxref/aliases.py +0 -0
  138. {py2max-0.5.1 → py2max-0.7.0}/py2max/maxref/data/bundle.json.gz +0 -0
  139. {py2max-0.5.1 → py2max-0.7.0}/py2max/py.typed +0 -0
  140. {py2max-0.5.1 → py2max-0.7.0}/tests/__init__.py +0 -0
  141. {py2max-0.5.1 → py2max-0.7.0}/tests/data/complex.maxpat +0 -0
  142. {py2max-0.5.1 → py2max-0.7.0}/tests/data/desc.maxpat +0 -0
  143. {py2max-0.5.1 → py2max-0.7.0}/tests/data/empty.maxpat +0 -0
  144. {py2max-0.5.1 → py2max-0.7.0}/tests/data/mydevice.amxd +0 -0
  145. {py2max-0.5.1 → py2max-0.7.0}/tests/data/mydevice2.amxd +0 -0
  146. {py2max-0.5.1 → py2max-0.7.0}/tests/data/nested.maxpat +0 -0
  147. {py2max-0.5.1 → py2max-0.7.0}/tests/data/simple.maxpat +0 -0
  148. {py2max-0.5.1 → py2max-0.7.0}/tests/data/tabular.maxpat +0 -0
  149. {py2max-0.5.1 → py2max-0.7.0}/tests/data/umenu.maxref.xml +0 -0
  150. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/README.md +0 -0
  151. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/db/category_db_demo.py +0 -0
  152. {py2max-0.5.1 → py2max-0.7.0}/tests/examples/db/maxref_db_demo.py +0 -0
  153. {py2max-0.5.1 → py2max-0.7.0}/tests/graphs/random/v30e33.tglf +0 -0
  154. {py2max-0.5.1 → py2max-0.7.0}/tests/test_abstraction.py +0 -0
  155. {py2max-0.5.1 → py2max-0.7.0}/tests/test_basic.py +0 -0
  156. {py2max-0.5.1 → py2max-0.7.0}/tests/test_beap.py +0 -0
  157. {py2max-0.5.1 → py2max-0.7.0}/tests/test_box_props.py +0 -0
  158. {py2max-0.5.1 → py2max-0.7.0}/tests/test_bpatcher.py +0 -0
  159. {py2max-0.5.1 → py2max-0.7.0}/tests/test_coll.py +0 -0
  160. {py2max-0.5.1 → py2max-0.7.0}/tests/test_colors.py +0 -0
  161. {py2max-0.5.1 → py2max-0.7.0}/tests/test_colors_theme.py +0 -0
  162. {py2max-0.5.1 → py2max-0.7.0}/tests/test_comment.py +0 -0
  163. {py2max-0.5.1 → py2max-0.7.0}/tests/test_connection_validation.py +0 -0
  164. {py2max-0.5.1 → py2max-0.7.0}/tests/test_db_schema.py +0 -0
  165. {py2max-0.5.1 → py2max-0.7.0}/tests/test_defaults.py +0 -0
  166. {py2max-0.5.1 → py2max-0.7.0}/tests/test_edit_operations.py +0 -0
  167. {py2max-0.5.1 → py2max-0.7.0}/tests/test_error_handling.py +0 -0
  168. {py2max-0.5.1 → py2max-0.7.0}/tests/test_ezdac.py +0 -0
  169. {py2max-0.5.1 → py2max-0.7.0}/tests/test_gen.py +0 -0
  170. {py2max-0.5.1 → py2max-0.7.0}/tests/test_group.py +0 -0
  171. {py2max-0.5.1 → py2max-0.7.0}/tests/test_js.py +0 -0
  172. {py2max-0.5.1 → py2max-0.7.0}/tests/test_js2max_runtime.py +0 -0
  173. {py2max-0.5.1 → py2max-0.7.0}/tests/test_kwds_filter.py +0 -0
  174. {py2max-0.5.1 → py2max-0.7.0}/tests/test_layout.py +0 -0
  175. {py2max-0.5.1 → py2max-0.7.0}/tests/test_layout_box_dims.py +0 -0
  176. {py2max-0.5.1 → py2max-0.7.0}/tests/test_layout_builtins.py +0 -0
  177. {py2max-0.5.1 → py2max-0.7.0}/tests/test_layout_coverage.py +0 -0
  178. {py2max-0.5.1 → py2max-0.7.0}/tests/test_layout_flow_crossings.py +0 -0
  179. {py2max-0.5.1 → py2max-0.7.0}/tests/test_layout_graph_layout.py +0 -0
  180. {py2max-0.5.1 → py2max-0.7.0}/tests/test_layout_grid_order.py +0 -0
  181. {py2max-0.5.1 → py2max-0.7.0}/tests/test_layout_overlaps.py +0 -0
  182. {py2max-0.5.1 → py2max-0.7.0}/tests/test_layout_vertical.py +0 -0
  183. {py2max-0.5.1 → py2max-0.7.0}/tests/test_linking.py +0 -0
  184. {py2max-0.5.1 → py2max-0.7.0}/tests/test_m4l.py +0 -0
  185. {py2max-0.5.1 → py2max-0.7.0}/tests/test_maxref_bundle.py +0 -0
  186. {py2max-0.5.1 → py2max-0.7.0}/tests/test_maxref_lazy.py +0 -0
  187. {py2max-0.5.1 → py2max-0.7.0}/tests/test_maxref_parser.py +0 -0
  188. {py2max-0.5.1 → py2max-0.7.0}/tests/test_mc_cycle.py +0 -0
  189. {py2max-0.5.1 → py2max-0.7.0}/tests/test_mc_poly.py +0 -0
  190. {py2max-0.5.1 → py2max-0.7.0}/tests/test_message.py +0 -0
  191. {py2max-0.5.1 → py2max-0.7.0}/tests/test_mypatch.py +0 -0
  192. {py2max-0.5.1 → py2max-0.7.0}/tests/test_nested.py +0 -0
  193. {py2max-0.5.1 → py2max-0.7.0}/tests/test_nested_patchers.py +0 -0
  194. {py2max-0.5.1 → py2max-0.7.0}/tests/test_number_tilde.py +0 -0
  195. {py2max-0.5.1 → py2max-0.7.0}/tests/test_numbers.py +0 -0
  196. {py2max-0.5.1 → py2max-0.7.0}/tests/test_param.py +0 -0
  197. {py2max-0.5.1 → py2max-0.7.0}/tests/test_param_placement.py +0 -0
  198. {py2max-0.5.1 → py2max-0.7.0}/tests/test_pitched_osc.py +0 -0
  199. {py2max-0.5.1 → py2max-0.7.0}/tests/test_porttypes.py +0 -0
  200. {py2max-0.5.1 → py2max-0.7.0}/tests/test_presets.py +0 -0
  201. {py2max-0.5.1 → py2max-0.7.0}/tests/test_pydantic.py +0 -0
  202. {py2max-0.5.1 → py2max-0.7.0}/tests/test_rnbo.py +0 -0
  203. {py2max-0.5.1 → py2max-0.7.0}/tests/test_rnbo_subpatcher.py +0 -0
  204. {py2max-0.5.1 → py2max-0.7.0}/tests/test_scripting_name.py +0 -0
  205. {py2max-0.5.1 → py2max-0.7.0}/tests/test_search.py +0 -0
  206. {py2max-0.5.1 → py2max-0.7.0}/tests/test_serialization.py +0 -0
  207. {py2max-0.5.1 → py2max-0.7.0}/tests/test_single_file.py +0 -0
  208. {py2max-0.5.1 → py2max-0.7.0}/tests/test_svg_fidelity.py +0 -0
  209. {py2max-0.5.1 → py2max-0.7.0}/tests/test_textbox_ports.py +0 -0
  210. {py2max-0.5.1 → py2max-0.7.0}/tests/test_transformers.py +0 -0
  211. {py2max-0.5.1 → py2max-0.7.0}/tests/test_transformers_e4.py +0 -0
  212. {py2max-0.5.1 → py2max-0.7.0}/tests/test_tree.py +0 -0
  213. {py2max-0.5.1 → py2max-0.7.0}/tests/test_tree_builder.py +0 -0
  214. {py2max-0.5.1 → py2max-0.7.0}/tests/test_tutorial_simple_synthesis.py +0 -0
  215. {py2max-0.5.1 → py2max-0.7.0}/tests/test_two_sines.py +0 -0
  216. {py2max-0.5.1 → py2max-0.7.0}/tests/test_umenu.py +0 -0
  217. {py2max-0.5.1 → py2max-0.7.0}/tests/test_validation.py +0 -0
  218. {py2max-0.5.1 → py2max-0.7.0}/tests/test_varname.py +0 -0
  219. {py2max-0.5.1 → py2max-0.7.0}/tests/test_wheel_bundle.py +0 -0
  220. {py2max-0.5.1 → py2max-0.7.0}/tests/test_zl_group.py +0 -0
@@ -1,5 +1,182 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.7.0]
4
+
5
+ ### Added
6
+
7
+ - Python 3.15 support: the test suite passes on 3.15, and CI tests it. CI set up each matrix Python but did not pass it to `uv sync`/`uv run`, which chose their own interpreter; `UV_PYTHON` now pins it.
8
+
9
+ - `py2max validate` lints py2max scripts as well as patches, ruff-style. A `.py` file is run with `save()` disabled, in a temporary working directory; every patch it builds is linted, and each finding points at the script line that made the box or cord. It takes several files or directories, `--select`/`--ignore` code prefixes, `# py2max: noqa: CODE` comments and `--list-rules`, and exits 1 if anything is reported. Running the script is the only way to see the patch it builds, since box ids and cords are usually computed.
10
+
11
+ ```bash
12
+ py2max validate examples/ --ignore W-OVERLAP
13
+ ```
14
+
15
+ - Eight lint warnings for patches that are valid but silent or stuck: `W-DAC-MONO` (signal in one channel of a stereo `dac~`/`ezdac~`), `W-ZERO-GAIN` (`*~` with no argument and an empty right inlet), `W-SIGNAL-UNUSED`, `W-BANG-IGNORED` (a bang into `adsr~`), `W-BANG-REPEATS` (only bangs into an arithmetic object), `W-METRO-INTERVAL` (a number box into `metro`'s on/off inlet), `W-ADSR-NO-GATE` (an `adsr~` whose output is used but whose gate inlet is empty) and `W-BIQUAD-ZERO` (a `biquad~` whose feed-forward coefficients a0-a2 are all 0, the default, so it outputs silence). Each caught a mistake in the repository's own examples: 27 example patches play in the left channel only.
16
+
17
+ - `Box.text` is settable. It writes where the text is stored (built boxes and loaded boxes differ), and does not update ports or maxclass.
18
+
19
+ - `lint()` reports a repeated cord (same outlet to same inlet) as `W-DUP-LINE`, a warning: Max loads such patches.
20
+
21
+ - `pinned=True` on any `add_*` call, or `box.pinned = True` afterwards (loaded boxes included), keeps a box where it is under every layout. Other boxes are moved off it. An explicit rect alone does not do this: the overlap pass, clustering and the whole-graph layouts move every box, which is what separates the boxes of a loaded patch. A pinned `inlet`/`outlet` keeps its place even if that renumbers ports. The flag is not saved to the file.
22
+
23
+ ```python
24
+ panel = p.add_textbox("panel", patching_rect=Rect(0, 0, 400, 300), pinned=True)
25
+ ```
26
+
27
+ - `MaxRefDB(path, read_only=True)` opens an existing file without creating or migrating the schema, and raises `DatabaseError` if it is not a current maxref database. The `db info`, `search`, `query` and `export` commands use it; they used to add 14 tables to any SQLite file passed to them.
28
+
29
+ - `device_type="midi_transformation"` and `"midi_generator"`: the Live 12 MIDI Tools device tags `natt` and `nagg`. Such `.amxd` files were rejected as an unknown type. The `project.amxdtype` value follows the same rule as the other three types and matches Max's own templates. Written devices have not been opened in Live.
30
+
31
+ ### Changed
32
+
33
+ - `ezdac~` is no longer pinned to the window's bottom-left. It takes the next layout slot like any other box, and keeps its 45x45 size. A class-default rect with x or y in (0, 1] no longer means a fraction of the window, and `LayoutManager.get_absolute_pos` is removed. `filtergraph~`'s default `(1, 1)` origin had the same effect by accident: it was placed in the bottom-right corner. To fix a box in place, pass `pinned=True`.
34
+
35
+ - An unknown layout name raises `LayoutError`, the documented exception, instead of `NotImplementedError`. `LayoutError` also subclasses `NotImplementedError`, so existing handlers still catch it.
36
+
37
+ - `py2max new` and `py2max optimize` accept `--layout columnar` and `--layout graph:<algorithm>`. `--flow-direction` is checked against the layout: `horizontal`/`vertical` for grid layouts and flow, `row`/`column` for matrix, none for columnar and `graph:*`. Before, `--flow-direction column` was accepted for grid and flow and silently meant horizontal.
38
+
39
+ - `add("<text>", x)` raises `TypeError`: extra positional arguments to `add()` with a string were silently dropped.
40
+
41
+ - An associated comment goes on the first side of its box (`comment_pos`, then above, right, below) that is clear of other boxes and inside the window. Layout rows can sit closer than a label is tall, so the label above a number box covered the box above it.
42
+
43
+ - A subpatcher box's `numinlets`/`numoutlets` follow the `inlet`/`outlet` boxes inside it as they are added, removed or replaced, including in loaded patches. They were synced only on save, and `get_inlet_count()`/`get_outlet_count()` read maxref's default for `p` (1 inlet, 0 outlets), so SVG export drew the wrong ports. Saved patches were already right. With no `inlet` left inside, the count stays at its last value, as `save()` has always written it.
44
+
45
+ - `W-SIGNAL-UNUSED` skips `sfrecord~` and `record~`: their signal outlet reports elapsed time or sync position, not audio.
46
+
47
+ - The examples in `tests/examples` pass `py2max validate`, and a test keeps them so. Fixes include stereo output, `metro` no longer driving oscillators, `adsr~` triggered by a `1` message instead of a bang, and filters with real parameters in place of `biquad~` with no coefficients (silent). The `preview/` patches and SVGs are regenerated.
48
+
49
+ - Associated comments (`comment=` on `add_*`) are sized by their text and placed beside their box after every layout. They took the box's width and height, so a comment above a `scope~` started 130 px up, often off the canvas, and one below a codebox overlapped it. They also took part in layout as ordinary boxes, so a second `optimize_layout()` moved them away from their box. `comment` must now be a `str`; `add_floatbox(0.5)` passed `0.5` as the comment and raises `TypeError`.
50
+
51
+ ### Security
52
+
53
+ - `maxpat_to_python` (`py2max convert maxpat-to-python`) pasted rect values, attribute keys, patchline ids and the source filename into the generated script unquoted, so a crafted `.maxpat` produced a script that ran arbitrary code. Values are now emitted with `repr()`, non-identifier keys go through `setattr`/`**{...}`, and a non-numeric rect raises `ValueError`.
54
+
55
+ ### Fixed
56
+
57
+ - `add_table`, `add_table_tilde` and `add_itable` loaded in Max as all-zero tables. Max saves `table_data` as a start index followed by the values (`size + 1` entries, first `0`); py2max wrote the values alone, so Max took the first value as the index. In the generative-music tutorial every note was then `mtof 0` (8.18 Hz), which you heard as modulation, not pitch. The leading `0` is now written.
58
+
59
+ - The generative-music tutorial (`tests/examples/tutorial/generative_music.py`, `docs/user_guide/tutorial.md`) made no sound. A bang into `/ N` outputs `0`, which stopped every pattern `metro`, and `adsr~` ignores bangs, so no envelope opened. A `counter` now divides the master clock, each voice sends `1` to `adsr~` (released by `@maxsustain`), and the tempo goes to the metro's interval inlet instead of its on/off inlet.
60
+
61
+ - `add("gen~ @title foo")` dropped everything after `gen~`.
62
+
63
+ - Flow layout (horizontal) put a cycle with no source box of its own on the "unconnected" level, as one column, when the patch had a source elsewhere. A patch that was only a cycle put every box on level 0. Each such cycle is now entered from one box, so it spreads across levels.
64
+
65
+ - `Patchline.to_tuple()` gave `order` 0 for a loaded patchline.
66
+
67
+ - A closed in-memory `MaxRefDB` raises `sqlite3.ProgrammingError` on use. Before, it opened a new, empty database.
68
+
69
+ - `layout="graph:hola"` killed the Python process when a box's only cord went to itself. hola's router fails a C++ assertion (`edgeLookup.size() > 1`), which Python cannot catch. Self-loops are now left out of the graph given to hola; they carry no layout information.
70
+
71
+ - `cluster_connected=True` gave a different layout per `PYTHONHASHSEED` when a large cluster split into equal-sized type groups: the groups were built by iterating a set. They are now built in box order.
72
+
73
+ - `add_box` accepted a second box with an id already in use. `_boxes` then held both while `_objects` kept only the newer, so cords and lookups hit the wrong box. This happened with `semantic_ids=True` and an explicit `id="cycle_1"`, or an explicit `id="obj-1"`. Generated ids now skip ids in use, and an explicit duplicate raises `InvalidObjectError`.
74
+
75
+ - Max discovery on macOS globbed `**/Max.app` through every app bundle in `/Applications`: about 7 s when no standalone Max was found. It now checks `Max*.app` and `*/Max*.app` only, and picks the newest by `Info.plist` version. Before, the winner between Max 8 and Max 9 depended on glob order.
76
+
77
+ - `add_coll`, `add_dict`, `add_table` and `add_itable` overwrote caller keywords with their defaults. `add_dict(data={...})` saved `{}`, and a caller's `saved_object_attributes` or `size` was replaced. Caller values now win, and `saved_object_attributes` is merged key by key. `add_dict` takes `data=` as a synonym for `dictionary=`.
78
+
79
+ - The CLI printed a traceback for a missing file, invalid patch JSON, a file that is not a SQLite database, or `db search` with no query. These now print one `Error:` line and exit 1; `-vv` keeps the traceback. `py2max db`, `db cache` and `convert` without a subcommand print their help.
80
+
81
+ - `MaxRefDB.by_category('MSP')` returned `[]`. maxref stores a comma-separated list of categories ("MSP Delays, Multichannel"), and the query compared the whole string. It now matches any one category, or its leading word, case ignored. `categories` lists single categories.
82
+
83
+ - A `save()` that raised during serialization left the target file truncated. The JSON is now built before the file is opened, still written in place for Max's reload.
84
+
85
+ - `add_subpatcher(text, patcher=Patcher())` saved the box's patcher as `{"patcher": {...}}`, which Max rejects. The supplied patcher was never attached to its parent, and only a top-level patcher is wrapped. Once attached, it inherits `auto_layout`, `on_invalid` and `validate_attrs` unless they were passed explicitly, as `Patcher(parent=...)` already did. These settings now resolve through the parent when read, not at construction, so patchers nested inside the supplied one inherit too.
86
+
87
+ - Loading and saving a patch blanked subpatcher `outlettype` (`["signal"]` became `[""]`). Port-count sync now resizes the existing list instead of replacing it.
88
+
89
+ - `Box.help()`, `help_text()` and `get_info()` looked up `maxclass`, which is `newobj` for text objects, so `add_textbox("cycle~").help()` found nothing. They now use the object name, as the port methods already did.
90
+
91
+ - `PY2MAX_DEBUG=true` (or any non-integer value) made `import py2max` raise `ValueError`. `0`, `false`, `no`, `off` and empty are false; anything else is true.
92
+
93
+ - `.amxd` files from Max with a `meta` chunk before `ptch`, bare JSON with no `mx@c` block, or frozen dependencies after the JSON failed to load. The reader walks the chunk list and parses only the JSON value. Encrypted (`ciph`) devices raise `PatcherIOError`.
94
+
95
+ - `from_file` rejected patches with raw control characters inside strings, which Max writes. Parsing is now non-strict. Invalid JSON, bad UTF-8 or a missing `patcher` object raise `PatcherIOError` instead of `JSONDecodeError`/`KeyError`.
96
+
97
+ - Explicit zero values were replaced by defaults: `add_intparam(initial=0)` saved `[1]`, `add_floatparam(initial=0.0)` saved `[0.5]`, `add_umenu(depth=0)` saved 1, and `add_codebox(numoutlets=0)` computed ports from the code.
98
+
99
+ - `outlettype` length now matches `numoutlets`. `add_bpatcher()` had 3 types for 1 outlet, and `encapsulate()` with no outgoing cords had 1 type for 0 outlets.
100
+
101
+ - `pitch2freq("Cb4")` returned B4 and `"B#3"` returned C3; Cb and B# now cross the octave boundary.
102
+
103
+ - `get_object_info()`, `Box.get_info()` and `MAXCLASS_DEFAULTS[name]` returned the cached dicts, so editing a result changed port counts and validation for the rest of the process. They now return copies.
104
+
105
+ - `PY2MAX_MAX_REFPAGES` pointing at a directory with no `*-ref/` folders gave 0 known objects, so validation and lint did nothing. It now warns and falls back to the bundled data. Refpages are read as UTF-8 regardless of locale; on Windows (cp1252) 15 of them failed to decode and were dropped.
106
+
107
+ - CLI: `py2max -vv info x` reset verbosity, because the `info --verbose` and `db search -v` flags shared the global `-v` destination.
108
+
109
+ - `add_textbox("")` raised an unpacking `ValueError`; it now raises `InvalidObjectError`. `add_itable()` with no name saved the text `"itable None"`.
110
+
111
+ - Lint, which runs on save, raised `AttributeError` for a loaded patch with no `rect` key.
112
+
113
+ - Explicit rects were taken for layout-placed ones when they matched the next grid slot, and were then moved by `optimize_layout()`. `add_textbox` called `get_pos()` even when given a rect, which also cost every explicit box a grid cell.
114
+
115
+ - `replace()` gave the replacement a fresh grid slot, so an explicit box became movable and a relayout shifted later boxes down. It now inherits the old box's slot or explicit status. `replace(old, Box(id=old.id, ...))` removed the new box from the id index; `find_by_id` returned `None`.
116
+
117
+ - `layout="columnar"` stacked each signal chain bottom-up: the column was ordered post-order, so every cord pointed up. The recursive `PatchGraph.topological_order` is removed; columns use `signal_order`.
118
+
119
+ - Matrix and columnar layouts kept removed boxes' categories and chain slots, so survivors stayed in rows a removed box had used, and `get_signal_chain_info()` listed removed ids. The off-canvas check is now skipped when there is no window size.
120
+
121
+ ## [0.6.0]
122
+
123
+ The default layout is now `"topdown"`: a vertical grid whose `optimize_layout()` sorts boxes into signal order and aligns ports.
124
+
125
+ Upgrading from 0.5.x:
126
+
127
+ - A patch that names no layout is placed top to bottom instead of left to right. `Patcher(layout="horizontal")` restores the 0.5 placement. Named layouts are unchanged. `py2max new --layout` defaults to `topdown` too, and `new --template stereo` now lays out its patch.
128
+
129
+ ### Added
130
+
131
+ - `optimize_layout(align_ports=True)` shifts boxes sideways so each cord from a box above drops straight; y is kept. It works with every layout manager and is off by default. Boxes with an explicit rect never move, and a shift that would put the box or its cord on another box is skipped. A window-anchored `ezdac~` shifts too, which is the common case: it no longer sits offset below a vertical chain.
132
+
133
+ - `layout="topdown"`: the `"vertical"` grid with `align_ports` on by default, so `optimize_layout()` aligns without the flag. `optimize_layout(align_ports=False)` still turns it off. Also a `py2max new --layout` choice.
134
+
135
+ - `Patcher(auto_layout=True)`: `save()`/`save_as()` runs `optimize_layout()` first, but only if boxes or cords changed since the last layout. A blanket re-run would discard an explicit `optimize_layout(...)` call's options, and flow recomputes every position. Moves made by hand after a layout are kept. Off by default, so `save()` never moves boxes unless asked. Subpatchers inherit the setting; patches loaded from a file have it off; `to_dict()`/`to_json()` never lay out.
136
+
137
+ ```python
138
+ p = Patcher("patch.maxpat", layout="topdown", auto_layout=True)
139
+ ```
140
+
141
+ ### Fixed
142
+
143
+ - Every `add_*` method raises `TypeError` when `patching_rect` is not 4 numbers. A misplaced positional argument used to be saved as the box's rect: `add_message("start", "stop")` stored the string `"stop"`, and `add_comment("note", box)` stored the box.
144
+
145
+ - `add_table(data=[...])` saved an empty table. The values go in `array=`, and `data` was on the attribute whitelist for every object, so the stray key passed without a warning. `add_table` now raises `TypeError` for `data=`. `data` is now a known attribute only for `dict`, so `add_coll(data=...)` (it takes `dictionary=`) warns as an unknown attribute. The examples and docs used both forms, so their tables and colls were empty.
146
+
147
+ - `optimize_layout()` raised `AttributeError: 'list' object has no attribute 'y'` on a patch of two or more boxes when one was added with `patching_rect=[x, y, w, h]`. The list was stored as given, and the overlap pass reads `rect.y`. Loaded patches were already converted; `add_box` now converts too.
148
+
149
+ ### Examples and docs
150
+
151
+ - The examples (`tests/examples/`) and the user guide used objects that do not exist in Max: `crossfade~`, `freeverb~`, `reverb~`, `chorus~`, `compressor~`, `eq~`, `inlet~`, `outlet~`. These are now real objects (`svf~`, `lores~`, `comb~`, `omx.comp~`, `selector~`, `tapin~`/`tapout~`, `inlet`/`outlet`).
152
+ - `biquad~` was given a frequency, Q or filter type, though it takes 5 coefficients.
153
+ - `delay~` was given a time in ms, though its arguments are in samples.
154
+ - Delay feedback now goes through `tapin~`/`tapout~`, since MSP rejects a signal loop through `delay~`.
155
+
156
+ - Several example patches could not make sound:
157
+ - The custom and modular synths never triggered their `adsr~`. `CustomPatcher.add_gate` now adds a `[1(` (note-on) and a `[0(` (note-off) to each one.
158
+ - The generative tutorial sent `start` to `metro`, which has no such message. Its stop message was never created: `add_message("start", "stop")` passed `"stop"` as the rect. Both are now `[1(` and `[0(`.
159
+ - The custom synth wired the wrong boxes into its oscillator mixer. It also sent the envelope into a filter inlet that does not exist; the envelope now scales a `*~`.
160
+ - The wavetable example read `wave~` from `table` objects. `wave~` reads a `buffer~`, so the example now writes WAV files that `buffer~` loads.
161
+ - The sequencer's `coll`s were empty, and its `select` was never connected.
162
+
163
+ - Subpatcher examples now wire the `add_subpatcher` box itself, with the `p` prefix Max needs. Before, they wired a second, empty `p` box.
164
+
165
+ - The matrix mixer is now an abstraction, `matrix-mixer.maxpat`: 4 signal inlets, a 5th inlet for `src dst gain` messages, and 4 outlets. A host patch uses it by file name.
166
+
167
+ - `svg_preview_demo.py` imported `export_svg` from `py2max`; it now imports from `py2max.export`.
168
+
169
+ ### Tests
170
+
171
+ - Test patches are built with `validate_connections=True` and use only cords Max accepts. Tests about invalid input are the exception.
172
+ - `metro` no longer feeds `cycle~` or `scope~`, nothing is wired out of `scope~`, and `gain~` no longer feeds `+`.
173
+ - The random-graph layout tests sample cords until the requested number are valid.
174
+ - The Pure Data `osc~` is now `cycle~`.
175
+
176
+ ### Removed
177
+
178
+ - The `signal_order` A/B test fixture. Layout tests run once again, and `build/test-output/signal_order_ab.md` is no longer written. It saved every patcher under `test_layout*` twice, which produced too many files to inspect.
179
+
3
180
  ## [0.5.1]
4
181
 
5
182
  ### Fixed
@@ -172,7 +349,7 @@ The rest is nine fixes, several of them long-standing and silent -- comments wri
172
349
 
173
350
  ### New: js2max -- a JavaScript counterpart that builds patches inside Max
174
351
 
175
- - **[`js2max/`](js2max/) is a second front end to the `.maxpat` format**, in TypeScript, doing the one thing this package cannot: Max embeds a JavaScript engine, and `v8` ships in current Max, so a script runs *inside an open patcher* and builds into it directly. py2max writes files Max later opens; js2max builds into the patch that is already open, from the same description. It serializes the other way too, and a file it wrote has been opened in Max.
352
+ - **[`js2max/`](https://github.com/shakfu/py2max/tree/main/js2max) is a second front end to the `.maxpat` format**, in TypeScript, doing the one thing this package cannot: Max embeds a JavaScript engine, and `v8` ships in current Max, so a script runs *inside an open patcher* and builds into it directly. py2max writes files Max later opens; js2max builds into the patch that is already open, from the same description. It serializes the other way too, and a file it wrote has been opened in Max.
176
353
 
177
354
  - **Nothing changes for Python users.** js2max adds no dependency -- its bundles are inert data, and nothing in py2max imports or executes them; the package keeps its zero runtime dependencies. It is a sibling directory with its own toolchain ([Bun](https://bun.sh)) and its own [CHANGELOG](https://github.com/shakfu/py2max/blob/main/js2max/CHANGELOG.md), where the detail lives. The two loadable bundles are committed, so a Max user needs no toolchain either.
178
355
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: py2max
3
- Version: 0.5.1
3
+ Version: 0.7.0
4
4
  Summary: A library for offline generation of Max/MSP patcher (.maxpat) files.
5
5
  Keywords: Max,maxpat,offline
6
6
  Author: Shakeeb Alireza
@@ -19,6 +19,7 @@ Classifier: Programming Language :: Python :: 3.11
19
19
  Classifier: Programming Language :: Python :: 3.12
20
20
  Classifier: Programming Language :: Python :: 3.13
21
21
  Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Programming Language :: Python :: 3.15
22
23
  Classifier: Operating System :: OS Independent
23
24
  Classifier: Typing :: Typed
24
25
  Requires-Dist: graph-layout>=0.4 ; extra == 'graph'
@@ -105,7 +106,8 @@ Generate Max for Live devices directly. `Patcher.save()` / `Patcher.from_file()`
105
106
  ```python
106
107
  from py2max import Patcher
107
108
 
108
- # device_type: "audio_effect" (default), "instrument", or "midi_effect"
109
+ # device_type: "audio_effect" (default), "instrument", "midi_effect",
110
+ # "midi_transformation" or "midi_generator" (Live 12 MIDI Tools)
109
111
  p = Patcher('gain.amxd', device_type='audio_effect')
110
112
  p.enable_presentation(devicewidth=120) # render Ableton's device strip
111
113
 
@@ -370,8 +372,9 @@ py2max preview demo.maxpat --open
370
372
  # Optimize layout
371
373
  py2max optimize demo.maxpat --layout flow
372
374
 
373
- # Validate connections
375
+ # Lint a patch, or the py2max script that builds it
374
376
  py2max validate demo.maxpat
377
+ py2max validate build_demo.py
375
378
  ```
376
379
 
377
380
  ### Interactive Server
@@ -68,7 +68,8 @@ Generate Max for Live devices directly. `Patcher.save()` / `Patcher.from_file()`
68
68
  ```python
69
69
  from py2max import Patcher
70
70
 
71
- # device_type: "audio_effect" (default), "instrument", or "midi_effect"
71
+ # device_type: "audio_effect" (default), "instrument", "midi_effect",
72
+ # "midi_transformation" or "midi_generator" (Live 12 MIDI Tools)
72
73
  p = Patcher('gain.amxd', device_type='audio_effect')
73
74
  p.enable_presentation(devicewidth=120) # render Ableton's device strip
74
75
 
@@ -333,8 +334,9 @@ py2max preview demo.maxpat --open
333
334
  # Optimize layout
334
335
  py2max optimize demo.maxpat --layout flow
335
336
 
336
- # Validate connections
337
+ # Lint a patch, or the py2max script that builds it
337
338
  py2max validate demo.maxpat
339
+ py2max validate build_demo.py
338
340
  ```
339
341
 
340
342
  ### Interactive Server
@@ -39,12 +39,13 @@ Example:
39
39
  >>> gain = p.add_textbox('gain~')
40
40
  >>> dac = p.add_textbox('ezdac~')
41
41
  >>> p.add_line(osc, gain)
42
- >>> p.add_line(gain, dac)
42
+ >>> p.add_line(gain, dac) # left
43
+ >>> p.add_line(gain, dac, inlet=1) # right
43
44
  >>> p.to_svg('/tmp/preview.svg') # Export to SVG
44
45
  >>> p.save()
45
46
  """
46
47
 
47
- __version__ = "0.5.1"
48
+ __version__ = "0.7.0"
48
49
 
49
50
  from .core import Box, Patcher, Patchline
50
51
  from .core.props import BoxProps, TextboxProps
@@ -0,0 +1,251 @@
1
+ """``py2max validate``: lint patches, and the scripts that build them.
2
+
3
+ A ``.maxpat``/``.maxhelp``/``.amxd`` file is loaded and linted. A ``.py``
4
+ script is run with ``save()``/``save_as()`` stubbed out, so it writes nothing,
5
+ and every patch it built is linted. Each box and cord records the script line
6
+ that made it, so findings point at the code to change. A ``# py2max: noqa``
7
+ or ``# py2max: noqa: CODE[, CODE]`` comment on that line suppresses them.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import contextlib
13
+ import io
14
+ import logging
15
+ import re
16
+ import os
17
+ import runpy
18
+ import sys
19
+ import tempfile
20
+ from dataclasses import dataclass
21
+ from pathlib import Path
22
+ from typing import Any, Generator, Iterable, List, Optional, Sequence, Tuple
23
+ from unittest import mock
24
+
25
+ from .lint import ERROR, RULES as LINT_RULES, Finding
26
+
27
+ E_SCRIPT = "E-SCRIPT"
28
+ #: every code ``validate`` can report, with a one-line description
29
+ RULES = {**LINT_RULES, E_SCRIPT: "the script raised or exited non-zero"}
30
+
31
+ PATCH_SUFFIXES = (".maxpat", ".maxhelp", ".amxd")
32
+ # prefixed with "py2max:", as ruff prefixes its file-level directive: ruff
33
+ # claims the unprefixed form and rejects W-DAC-MONO as one of its codes
34
+ _NOQA = re.compile(r"#\s*py2max:\s*noqa(?::\s*(?P<codes>[\w\-, ]+))?", re.IGNORECASE)
35
+
36
+
37
+ @dataclass
38
+ class Report:
39
+ """A finding with the file (and line) it is reported against."""
40
+
41
+ path: Path
42
+ finding: Finding
43
+ patch: Optional[str] = None # which patch, when a script built several
44
+
45
+ @property
46
+ def line(self) -> Optional[int]:
47
+ src = self.finding.source
48
+ return src[1] if src else None
49
+
50
+ def __str__(self) -> str:
51
+ f = self.finding
52
+ where = f"{self.path}:{self.line}" if self.line else f"{self.path}"
53
+ target = ""
54
+ if f.line is not None:
55
+ s, so, d, di = f.line
56
+ target = f" [{s}:{so} -> {d}:{di}]"
57
+ elif f.obj_id is not None:
58
+ target = f" [{f.obj_id}]"
59
+ patch = f" ({self.patch})" if self.patch else ""
60
+ return f"{where}: {f.code} {f.message}{target}{patch}"
61
+
62
+
63
+ def _script_line(script: Path) -> Optional[Tuple[str, int]]:
64
+ """(file, line) of the innermost frame running ``script``, if any."""
65
+ frame = sys._getframe(1)
66
+ while frame is not None:
67
+ if Path(frame.f_code.co_filename).resolve() == script:
68
+ return (str(script), frame.f_lineno)
69
+ frame = frame.f_back # type: ignore[assignment]
70
+ return None
71
+
72
+
73
+ @contextlib.contextmanager
74
+ def _instrumented(script: Path) -> Generator[List[Any], None, None]:
75
+ """Record root patchers, tag boxes and cords with their script line, and
76
+ stop the script writing files. Yields the list of root patchers."""
77
+ from .core.factory import BoxFactoryMixin
78
+ from .core.patcher import Patcher
79
+
80
+ roots: List[Any] = []
81
+ init, register, add_line = (
82
+ Patcher.__init__,
83
+ BoxFactoryMixin._register_box,
84
+ BoxFactoryMixin.add_line,
85
+ )
86
+
87
+ def patched_init(self: Any, *args: Any, **kwds: Any) -> None:
88
+ init(self, *args, **kwds)
89
+ if getattr(self, "_parent", None) is None:
90
+ roots.append(self)
91
+
92
+ def patched_register(self: Any, box: Any, *args: Any, **kwds: Any) -> Any:
93
+ box._source = _script_line(script)
94
+ return register(self, box, *args, **kwds)
95
+
96
+ def patched_add_line(self: Any, *args: Any, **kwds: Any) -> Any:
97
+ line = add_line(self, *args, **kwds)
98
+ setattr(line, "_source", _script_line(script))
99
+ return line
100
+
101
+ logger = logging.getLogger("py2max")
102
+ level = logger.level
103
+ logger.setLevel(logging.CRITICAL) # lint reports what the run would log
104
+ try:
105
+ with contextlib.ExitStack() as stack:
106
+ for target, attr, new in (
107
+ (Patcher, "__init__", patched_init),
108
+ (BoxFactoryMixin, "_register_box", patched_register),
109
+ (BoxFactoryMixin, "add_line", patched_add_line),
110
+ (Patcher, "save", lambda self, *a, **k: None),
111
+ (Patcher, "save_as", lambda self, *a, **k: None),
112
+ ):
113
+ stack.enter_context(mock.patch.object(target, attr, new))
114
+ yield roots
115
+ finally:
116
+ logger.setLevel(level)
117
+
118
+
119
+ def _run_script(script: Path) -> Tuple[List[Any], List[Finding]]:
120
+ """Run ``script``; return the root patchers it built and any run failure.
121
+
122
+ It runs in a temporary working directory, so files it writes by relative
123
+ path (an SVG export, say) are discarded. Absolute paths are not covered.
124
+ """
125
+ failures: List[Finding] = []
126
+ saved_argv, saved_path, saved_cwd = sys.argv, list(sys.path), os.getcwd()
127
+ sys.argv = [str(script)]
128
+ sys.path.insert(0, str(script.parent))
129
+ tmp = tempfile.TemporaryDirectory(prefix="py2max-validate-")
130
+ os.chdir(tmp.name)
131
+ try:
132
+ with contextlib.ExitStack() as stack:
133
+ roots = stack.enter_context(_instrumented(script))
134
+ stack.enter_context(contextlib.redirect_stdout(io.StringIO()))
135
+ stack.enter_context(contextlib.redirect_stderr(io.StringIO()))
136
+ try:
137
+ runpy.run_path(str(script), run_name="__main__")
138
+ except SystemExit as exc:
139
+ if exc.code not in (None, 0):
140
+ failures.append(
141
+ Finding(E_SCRIPT, ERROR, f"exited with status {exc.code}")
142
+ )
143
+ except Exception as exc: # report, do not crash the whole run
144
+ tb = exc.__traceback__
145
+ where = None
146
+ while tb is not None:
147
+ if Path(tb.tb_frame.f_code.co_filename).resolve() == script:
148
+ where = (str(script), tb.tb_lineno)
149
+ tb = tb.tb_next
150
+ failures.append(
151
+ Finding(
152
+ E_SCRIPT,
153
+ ERROR,
154
+ f"{type(exc).__name__}: {exc}",
155
+ source=where,
156
+ )
157
+ )
158
+ finally:
159
+ os.chdir(saved_cwd)
160
+ tmp.cleanup()
161
+ sys.argv, sys.path[:] = saved_argv, saved_path
162
+ return roots, failures
163
+
164
+
165
+ def _suppressed(report: Report, lines: Sequence[str]) -> bool:
166
+ """True if the reported line carries a ``# py2max: noqa`` covering its code."""
167
+ n = report.line
168
+ if not n or n > len(lines):
169
+ return False
170
+ m = _NOQA.search(lines[n - 1])
171
+ if m is None:
172
+ return False
173
+ codes = m.group("codes")
174
+ if not codes:
175
+ return True
176
+ wanted = {c.strip().upper() for c in codes.split(",") if c.strip()}
177
+ return report.finding.code.upper() in wanted
178
+
179
+
180
+ def check_file(path: Path) -> List[Report]:
181
+ """Lint one patch file or py2max script."""
182
+ from .core.patcher import Patcher
183
+
184
+ if path.suffix.lower() == ".py":
185
+ script = path.resolve()
186
+ roots, failures = _run_script(script)
187
+ reports = [Report(path, f) for f in failures]
188
+ named = len(roots) > 1
189
+ for p in roots:
190
+ label = Path(str(p._path)).name if named and p._path else None
191
+ reports += [Report(path, f, label) for f in p.lint()]
192
+ lines = script.read_text(encoding="utf-8").splitlines()
193
+ return [r for r in reports if not _suppressed(r, lines)]
194
+ patcher = Patcher.from_file(path)
195
+ return [Report(path, f) for f in patcher.lint()]
196
+
197
+
198
+ def _uses_py2max(path: Path) -> bool:
199
+ try:
200
+ return "py2max" in path.read_text(encoding="utf-8")
201
+ except (OSError, UnicodeDecodeError):
202
+ return False
203
+
204
+
205
+ def collect(paths: Iterable[Path]) -> List[Path]:
206
+ """Expand directories into the patch files and py2max scripts they hold.
207
+
208
+ A ``.py`` file found in a directory is run only if it mentions py2max;
209
+ one named on the command line always is.
210
+ """
211
+ found: List[Path] = []
212
+ for path in paths:
213
+ if not path.is_dir():
214
+ found.append(path)
215
+ continue
216
+ for child in sorted(path.rglob("*")):
217
+ parts = child.relative_to(path).parts
218
+ if any(p.startswith(".") or p == "__pycache__" for p in parts):
219
+ continue
220
+ if child.suffix.lower() in PATCH_SUFFIXES or (
221
+ child.suffix == ".py" and _uses_py2max(child)
222
+ ):
223
+ found.append(child)
224
+ return found
225
+
226
+
227
+ def _matches(code: str, prefixes: Optional[Sequence[str]]) -> bool:
228
+ return any(code.upper().startswith(p.upper()) for p in prefixes or ())
229
+
230
+
231
+ def validate(
232
+ paths: Iterable[Path],
233
+ select: Optional[Sequence[str]] = None,
234
+ ignore: Optional[Sequence[str]] = None,
235
+ ) -> List[Report]:
236
+ """Lint every patch and script under ``paths``.
237
+
238
+ ``select`` and ``ignore`` are code prefixes, as in ruff: ``W-DAC`` matches
239
+ ``W-DAC-MONO``, ``E`` every error.
240
+ """
241
+ reports: List[Report] = []
242
+ for path in collect(paths):
243
+ for r in check_file(path):
244
+ code = r.finding.code
245
+ if select and not _matches(code, select):
246
+ continue
247
+ if _matches(code, ignore):
248
+ continue
249
+ reports.append(r)
250
+ reports.sort(key=lambda r: (str(r.path), r.line or 0, r.finding.code))
251
+ return reports