diff --git a/.gitattributes b/.gitattributes index 5c69de19ff330e87f7395c81887259e72d74207c..0b0d9d11f9f4069be59332a3e2a30b10278e5e69 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3408,3 +3408,9 @@ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/yue_Ha platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/zh.dat filter=lfs diff=lfs merge=lfs -text platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/zh_Hant.dat filter=lfs diff=lfs merge=lfs -text platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/zu.dat filter=lfs diff=lfs merge=lfs -text +platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/emoji1_db.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/gemoji_db.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/twemoji_db.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/compiler.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/cluster.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/metadata.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88180878caf5bffa084c6bbf6c9d0ef35de2916a Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/_argcomplete.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/_argcomplete.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7c45e931ecd72e055d732be0cc2987f72431343 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/_argcomplete.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/_version.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/_version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1414b540d689d06f09d028969386e6425600f43 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/_version.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/cacheprovider.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/cacheprovider.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c09acc677d3c22a8366ffc9b4385d2b721476f6a Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/cacheprovider.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/capture.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/capture.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7e66477894751a83e2446ff19552a4d3f11f55e Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/capture.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/compat.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/compat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9636ca28f3890e009cd9f0835977186462ac9000 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/compat.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/debugging.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/debugging.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..205675114f947b1f2499f91a8dff8373f7a6b25f Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/debugging.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/deprecated.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/deprecated.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..303ed2fa2987056c46a496feb27e0fdb0b9630c7 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/deprecated.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/doctest.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/doctest.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7888d5a75c263df2c3f3b21f700c2716a34ded40 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/doctest.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/faulthandler.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/faulthandler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be37edcd8a5e5c46a376983f5492779a8e347e70 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/faulthandler.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/fixtures.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/fixtures.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7005a29bb472ce6777fd07c5413786a914113aa Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/fixtures.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/freeze_support.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/freeze_support.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52ba1b5b3a743f23a7368b59ffb405012c55dfda Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/freeze_support.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/helpconfig.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/helpconfig.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e57cff111d4375b2a01fcc82b4d1e973c2a6c693 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/helpconfig.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/hookspec.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/hookspec.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91fa199a8a73a6a02d4ea634348b9e57bf2be3e2 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/hookspec.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/junitxml.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/junitxml.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a029dc622a1634db9e1f330dbfc4cbec771b134 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/junitxml.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/legacypath.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/legacypath.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5809c93195eed0625830b7057444ec9a2c543ac7 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/legacypath.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/logging.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/logging.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4cb3535b778b253fdaecaa3b7c111e2da2dcda6 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/logging.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/main.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/main.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..754b072fd67a68a710b8a4657557d84b882b31df Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/main.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/monkeypatch.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/monkeypatch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f44c8e710f1d70d4bc6b8ffea42be00ee40c86b5 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/monkeypatch.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/nodes.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/nodes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af81e1ba9b9d6dad4531b98c9fd27c3e14f70387 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/nodes.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/nose.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/nose.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c121131ce16c49275b264885550cf07a0c17113 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/nose.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/outcomes.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/outcomes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..692a0fde42333b9ffbf8850208ce1d76a8f7a503 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/outcomes.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/pastebin.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/pastebin.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d032d0e22dd58c9e4dff45f02d0c1ba55f2824e Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/pastebin.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/pathlib.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/pathlib.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69a6109868d6ac34c71d7fe539c6149f0c850897 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/pathlib.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/pytester.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/pytester.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcd195bd8ebafca71489cdff9ed0bb4e2a1f6c1b Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/pytester.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/pytester_assertions.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/pytester_assertions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5fae0eb7b1b51789d9de80e029b1fc54a8fa48a Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/pytester_assertions.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/python.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/python.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3d5165c2f75aec185752dc94456f2cd2def675b Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/python.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/python_api.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/python_api.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ecf2356a3891a80c5aeeffd7d96afb355547d0c Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/python_api.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/python_path.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/python_path.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dba8f73df26f70dfe9ebaaff6aea5a4bb450511a Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/python_path.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/recwarn.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/recwarn.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91c9c2e6afb4a073e3b9ede2f5c4f9db07a7215e Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/recwarn.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/reports.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/reports.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8376aebf9492b4f9964053b4d41349934e8c656 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/reports.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/runner.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/runner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9533ed9103625d2919e8e2d303f23c9d5a061860 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/runner.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/scope.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/scope.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5248789a388aadad52669e98e6b8bec880c74087 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/scope.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/setuponly.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/setuponly.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd52794caa9cff6232c12fcbe053226aceb159bd Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/setuponly.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/setupplan.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/setupplan.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd50e5d58be1df49f3329427cb7f86f401cbaca8 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/setupplan.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/skipping.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/skipping.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f23a48d7954a4fd688c301d5a888a261c488c541 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/skipping.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/stash.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/stash.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..480a501395282b60d47133aceaa3d7a039f9251c Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/stash.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/stepwise.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/stepwise.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..763dad72f282c797ac0d493963d16d2296ad510f Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/stepwise.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/terminal.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/terminal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92fe31f2b4a4b300c0f5d53837f0ef0b8d08a736 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/terminal.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/threadexception.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/threadexception.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ded36d023868cd055ab9e19d5e6db5356a0c46d Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/threadexception.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/timing.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/timing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..549f983be276b83a5ae3db4d65eefe4bcfb024ce Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/timing.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/tmpdir.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/tmpdir.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a1784b7dfeb8b58e221b0fdcedf50404faacc0c Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/tmpdir.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/unittest.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/unittest.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf8541437816119bb37a698364071d079fd324ff Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/unittest.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/unraisableexception.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/unraisableexception.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..050add70666cbc8545f83d7ae06dd2c707b5bbb9 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/unraisableexception.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/warning_types.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/warning_types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3b11950541fce2a64fe9d48d78ce210e7a0b5fd Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/warning_types.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/warnings.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/warnings.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6f5ca72303a141eb33cb29223de12017cbbff8a Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__pycache__/warnings.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_code/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_code/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..511d0dde661dfb97378f76f1d17cbc55e150ef80 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_code/__init__.py @@ -0,0 +1,22 @@ +"""Python inspection/code generation API.""" +from .code import Code +from .code import ExceptionInfo +from .code import filter_traceback +from .code import Frame +from .code import getfslineno +from .code import Traceback +from .code import TracebackEntry +from .source import getrawcode +from .source import Source + +__all__ = [ + "Code", + "ExceptionInfo", + "filter_traceback", + "Frame", + "getfslineno", + "getrawcode", + "Traceback", + "TracebackEntry", + "Source", +] diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_code/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_code/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88b3406f21ac633498530b26e0d06fc3010767f5 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_code/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_code/__pycache__/code.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_code/__pycache__/code.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..183978c0921fd61412ac1a3c93c868937d0ae4cc Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_code/__pycache__/code.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_code/__pycache__/source.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_code/__pycache__/source.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ebbd77d175331198eaa085cb37b468a431688b8 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_code/__pycache__/source.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_code/code.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_code/code.py new file mode 100644 index 0000000000000000000000000000000000000000..9b051332baf485841961181521fbdc5ac0ab4b17 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_code/code.py @@ -0,0 +1,1337 @@ +import ast +import dataclasses +import inspect +import os +import re +import sys +import traceback +from inspect import CO_VARARGS +from inspect import CO_VARKEYWORDS +from io import StringIO +from pathlib import Path +from traceback import format_exception_only +from types import CodeType +from types import FrameType +from types import TracebackType +from typing import Any +from typing import Callable +from typing import ClassVar +from typing import Dict +from typing import Generic +from typing import Iterable +from typing import List +from typing import Mapping +from typing import Optional +from typing import overload +from typing import Pattern +from typing import Sequence +from typing import Set +from typing import Tuple +from typing import Type +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union + +import pluggy + +import _pytest +from _pytest._code.source import findsource +from _pytest._code.source import getrawcode +from _pytest._code.source import getstatementrange_ast +from _pytest._code.source import Source +from _pytest._io import TerminalWriter +from _pytest._io.saferepr import safeformat +from _pytest._io.saferepr import saferepr +from _pytest.compat import final +from _pytest.compat import get_real_func +from _pytest.deprecated import check_ispytest +from _pytest.pathlib import absolutepath +from _pytest.pathlib import bestrelpath + +if TYPE_CHECKING: + from typing_extensions import Final + from typing_extensions import Literal + from typing_extensions import SupportsIndex + + _TracebackStyle = Literal["long", "short", "line", "no", "native", "value", "auto"] + +if sys.version_info[:2] < (3, 11): + from exceptiongroup import BaseExceptionGroup + + +class Code: + """Wrapper around Python code objects.""" + + __slots__ = ("raw",) + + def __init__(self, obj: CodeType) -> None: + self.raw = obj + + @classmethod + def from_function(cls, obj: object) -> "Code": + return cls(getrawcode(obj)) + + def __eq__(self, other): + return self.raw == other.raw + + # Ignore type because of https://github.com/python/mypy/issues/4266. + __hash__ = None # type: ignore + + @property + def firstlineno(self) -> int: + return self.raw.co_firstlineno - 1 + + @property + def name(self) -> str: + return self.raw.co_name + + @property + def path(self) -> Union[Path, str]: + """Return a path object pointing to source code, or an ``str`` in + case of ``OSError`` / non-existing file.""" + if not self.raw.co_filename: + return "" + try: + p = absolutepath(self.raw.co_filename) + # maybe don't try this checking + if not p.exists(): + raise OSError("path check failed.") + return p + except OSError: + # XXX maybe try harder like the weird logic + # in the standard lib [linecache.updatecache] does? + return self.raw.co_filename + + @property + def fullsource(self) -> Optional["Source"]: + """Return a _pytest._code.Source object for the full source file of the code.""" + full, _ = findsource(self.raw) + return full + + def source(self) -> "Source": + """Return a _pytest._code.Source object for the code object's source only.""" + # return source only for that part of code + return Source(self.raw) + + def getargs(self, var: bool = False) -> Tuple[str, ...]: + """Return a tuple with the argument names for the code object. + + If 'var' is set True also return the names of the variable and + keyword arguments when present. + """ + # Handy shortcut for getting args. + raw = self.raw + argcount = raw.co_argcount + if var: + argcount += raw.co_flags & CO_VARARGS + argcount += raw.co_flags & CO_VARKEYWORDS + return raw.co_varnames[:argcount] + + +class Frame: + """Wrapper around a Python frame holding f_locals and f_globals + in which expressions can be evaluated.""" + + __slots__ = ("raw",) + + def __init__(self, frame: FrameType) -> None: + self.raw = frame + + @property + def lineno(self) -> int: + return self.raw.f_lineno - 1 + + @property + def f_globals(self) -> Dict[str, Any]: + return self.raw.f_globals + + @property + def f_locals(self) -> Dict[str, Any]: + return self.raw.f_locals + + @property + def code(self) -> Code: + return Code(self.raw.f_code) + + @property + def statement(self) -> "Source": + """Statement this frame is at.""" + if self.code.fullsource is None: + return Source("") + return self.code.fullsource.getstatement(self.lineno) + + def eval(self, code, **vars): + """Evaluate 'code' in the frame. + + 'vars' are optional additional local variables. + + Returns the result of the evaluation. + """ + f_locals = self.f_locals.copy() + f_locals.update(vars) + return eval(code, self.f_globals, f_locals) + + def repr(self, object: object) -> str: + """Return a 'safe' (non-recursive, one-line) string repr for 'object'.""" + return saferepr(object) + + def getargs(self, var: bool = False): + """Return a list of tuples (name, value) for all arguments. + + If 'var' is set True, also include the variable and keyword arguments + when present. + """ + retval = [] + for arg in self.code.getargs(var): + try: + retval.append((arg, self.f_locals[arg])) + except KeyError: + pass # this can occur when using Psyco + return retval + + +class TracebackEntry: + """A single entry in a Traceback.""" + + __slots__ = ("_rawentry", "_repr_style") + + def __init__( + self, + rawentry: TracebackType, + repr_style: Optional['Literal["short", "long"]'] = None, + ) -> None: + self._rawentry: "Final" = rawentry + self._repr_style: "Final" = repr_style + + def with_repr_style( + self, repr_style: Optional['Literal["short", "long"]'] + ) -> "TracebackEntry": + return TracebackEntry(self._rawentry, repr_style) + + @property + def lineno(self) -> int: + return self._rawentry.tb_lineno - 1 + + @property + def frame(self) -> Frame: + return Frame(self._rawentry.tb_frame) + + @property + def relline(self) -> int: + return self.lineno - self.frame.code.firstlineno + + def __repr__(self) -> str: + return "" % (self.frame.code.path, self.lineno + 1) + + @property + def statement(self) -> "Source": + """_pytest._code.Source object for the current statement.""" + source = self.frame.code.fullsource + assert source is not None + return source.getstatement(self.lineno) + + @property + def path(self) -> Union[Path, str]: + """Path to the source code.""" + return self.frame.code.path + + @property + def locals(self) -> Dict[str, Any]: + """Locals of underlying frame.""" + return self.frame.f_locals + + def getfirstlinesource(self) -> int: + return self.frame.code.firstlineno + + def getsource( + self, astcache: Optional[Dict[Union[str, Path], ast.AST]] = None + ) -> Optional["Source"]: + """Return failing source code.""" + # we use the passed in astcache to not reparse asttrees + # within exception info printing + source = self.frame.code.fullsource + if source is None: + return None + key = astnode = None + if astcache is not None: + key = self.frame.code.path + if key is not None: + astnode = astcache.get(key, None) + start = self.getfirstlinesource() + try: + astnode, _, end = getstatementrange_ast( + self.lineno, source, astnode=astnode + ) + except SyntaxError: + end = self.lineno + 1 + else: + if key is not None and astcache is not None: + astcache[key] = astnode + return source[start:end] + + source = property(getsource) + + def ishidden(self, excinfo: Optional["ExceptionInfo[BaseException]"]) -> bool: + """Return True if the current frame has a var __tracebackhide__ + resolving to True. + + If __tracebackhide__ is a callable, it gets called with the + ExceptionInfo instance and can decide whether to hide the traceback. + + Mostly for internal use. + """ + tbh: Union[ + bool, Callable[[Optional[ExceptionInfo[BaseException]]], bool] + ] = False + for maybe_ns_dct in (self.frame.f_locals, self.frame.f_globals): + # in normal cases, f_locals and f_globals are dictionaries + # however via `exec(...)` / `eval(...)` they can be other types + # (even incorrect types!). + # as such, we suppress all exceptions while accessing __tracebackhide__ + try: + tbh = maybe_ns_dct["__tracebackhide__"] + except Exception: + pass + else: + break + if tbh and callable(tbh): + return tbh(excinfo) + return tbh + + def __str__(self) -> str: + name = self.frame.code.name + try: + line = str(self.statement).lstrip() + except KeyboardInterrupt: + raise + except BaseException: + line = "???" + # This output does not quite match Python's repr for traceback entries, + # but changing it to do so would break certain plugins. See + # https://github.com/pytest-dev/pytest/pull/7535/ for details. + return " File %r:%d in %s\n %s\n" % ( + str(self.path), + self.lineno + 1, + name, + line, + ) + + @property + def name(self) -> str: + """co_name of underlying code.""" + return self.frame.code.raw.co_name + + +class Traceback(List[TracebackEntry]): + """Traceback objects encapsulate and offer higher level access to Traceback entries.""" + + def __init__( + self, + tb: Union[TracebackType, Iterable[TracebackEntry]], + ) -> None: + """Initialize from given python traceback object and ExceptionInfo.""" + if isinstance(tb, TracebackType): + + def f(cur: TracebackType) -> Iterable[TracebackEntry]: + cur_: Optional[TracebackType] = cur + while cur_ is not None: + yield TracebackEntry(cur_) + cur_ = cur_.tb_next + + super().__init__(f(tb)) + else: + super().__init__(tb) + + def cut( + self, + path: Optional[Union["os.PathLike[str]", str]] = None, + lineno: Optional[int] = None, + firstlineno: Optional[int] = None, + excludepath: Optional["os.PathLike[str]"] = None, + ) -> "Traceback": + """Return a Traceback instance wrapping part of this Traceback. + + By providing any combination of path, lineno and firstlineno, the + first frame to start the to-be-returned traceback is determined. + + This allows cutting the first part of a Traceback instance e.g. + for formatting reasons (removing some uninteresting bits that deal + with handling of the exception/traceback). + """ + path_ = None if path is None else os.fspath(path) + excludepath_ = None if excludepath is None else os.fspath(excludepath) + for x in self: + code = x.frame.code + codepath = code.path + if path is not None and str(codepath) != path_: + continue + if ( + excludepath is not None + and isinstance(codepath, Path) + and excludepath_ in (str(p) for p in codepath.parents) # type: ignore[operator] + ): + continue + if lineno is not None and x.lineno != lineno: + continue + if firstlineno is not None and x.frame.code.firstlineno != firstlineno: + continue + return Traceback(x._rawentry) + return self + + @overload + def __getitem__(self, key: "SupportsIndex") -> TracebackEntry: + ... + + @overload + def __getitem__(self, key: slice) -> "Traceback": + ... + + def __getitem__( + self, key: Union["SupportsIndex", slice] + ) -> Union[TracebackEntry, "Traceback"]: + if isinstance(key, slice): + return self.__class__(super().__getitem__(key)) + else: + return super().__getitem__(key) + + def filter( + self, + # TODO(py38): change to positional only. + _excinfo_or_fn: Union[ + "ExceptionInfo[BaseException]", + Callable[[TracebackEntry], bool], + ], + ) -> "Traceback": + """Return a Traceback instance with certain items removed. + + If the filter is an `ExceptionInfo`, removes all the ``TracebackEntry``s + which are hidden (see ishidden() above). + + Otherwise, the filter is a function that gets a single argument, a + ``TracebackEntry`` instance, and should return True when the item should + be added to the ``Traceback``, False when not. + """ + if isinstance(_excinfo_or_fn, ExceptionInfo): + fn = lambda x: not x.ishidden(_excinfo_or_fn) # noqa: E731 + else: + fn = _excinfo_or_fn + return Traceback(filter(fn, self)) + + def recursionindex(self) -> Optional[int]: + """Return the index of the frame/TracebackEntry where recursion originates if + appropriate, None if no recursion occurred.""" + cache: Dict[Tuple[Any, int, int], List[Dict[str, Any]]] = {} + for i, entry in enumerate(self): + # id for the code.raw is needed to work around + # the strange metaprogramming in the decorator lib from pypi + # which generates code objects that have hash/value equality + # XXX needs a test + key = entry.frame.code.path, id(entry.frame.code.raw), entry.lineno + # print "checking for recursion at", key + values = cache.setdefault(key, []) + if values: + f = entry.frame + loc = f.f_locals + for otherloc in values: + if otherloc == loc: + return i + values.append(entry.frame.f_locals) + return None + + +E = TypeVar("E", bound=BaseException, covariant=True) + + +@final +@dataclasses.dataclass +class ExceptionInfo(Generic[E]): + """Wraps sys.exc_info() objects and offers help for navigating the traceback.""" + + _assert_start_repr: ClassVar = "AssertionError('assert " + + _excinfo: Optional[Tuple[Type["E"], "E", TracebackType]] + _striptext: str + _traceback: Optional[Traceback] + + def __init__( + self, + excinfo: Optional[Tuple[Type["E"], "E", TracebackType]], + striptext: str = "", + traceback: Optional[Traceback] = None, + *, + _ispytest: bool = False, + ) -> None: + check_ispytest(_ispytest) + self._excinfo = excinfo + self._striptext = striptext + self._traceback = traceback + + @classmethod + def from_exception( + cls, + # Ignoring error: "Cannot use a covariant type variable as a parameter". + # This is OK to ignore because this class is (conceptually) readonly. + # See https://github.com/python/mypy/issues/7049. + exception: E, # type: ignore[misc] + exprinfo: Optional[str] = None, + ) -> "ExceptionInfo[E]": + """Return an ExceptionInfo for an existing exception. + + The exception must have a non-``None`` ``__traceback__`` attribute, + otherwise this function fails with an assertion error. This means that + the exception must have been raised, or added a traceback with the + :py:meth:`~BaseException.with_traceback()` method. + + :param exprinfo: + A text string helping to determine if we should strip + ``AssertionError`` from the output. Defaults to the exception + message/``__str__()``. + + .. versionadded:: 7.4 + """ + assert ( + exception.__traceback__ + ), "Exceptions passed to ExcInfo.from_exception(...) must have a non-None __traceback__." + exc_info = (type(exception), exception, exception.__traceback__) + return cls.from_exc_info(exc_info, exprinfo) + + @classmethod + def from_exc_info( + cls, + exc_info: Tuple[Type[E], E, TracebackType], + exprinfo: Optional[str] = None, + ) -> "ExceptionInfo[E]": + """Like :func:`from_exception`, but using old-style exc_info tuple.""" + _striptext = "" + if exprinfo is None and isinstance(exc_info[1], AssertionError): + exprinfo = getattr(exc_info[1], "msg", None) + if exprinfo is None: + exprinfo = saferepr(exc_info[1]) + if exprinfo and exprinfo.startswith(cls._assert_start_repr): + _striptext = "AssertionError: " + + return cls(exc_info, _striptext, _ispytest=True) + + @classmethod + def from_current( + cls, exprinfo: Optional[str] = None + ) -> "ExceptionInfo[BaseException]": + """Return an ExceptionInfo matching the current traceback. + + .. warning:: + + Experimental API + + :param exprinfo: + A text string helping to determine if we should strip + ``AssertionError`` from the output. Defaults to the exception + message/``__str__()``. + """ + tup = sys.exc_info() + assert tup[0] is not None, "no current exception" + assert tup[1] is not None, "no current exception" + assert tup[2] is not None, "no current exception" + exc_info = (tup[0], tup[1], tup[2]) + return ExceptionInfo.from_exc_info(exc_info, exprinfo) + + @classmethod + def for_later(cls) -> "ExceptionInfo[E]": + """Return an unfilled ExceptionInfo.""" + return cls(None, _ispytest=True) + + def fill_unfilled(self, exc_info: Tuple[Type[E], E, TracebackType]) -> None: + """Fill an unfilled ExceptionInfo created with ``for_later()``.""" + assert self._excinfo is None, "ExceptionInfo was already filled" + self._excinfo = exc_info + + @property + def type(self) -> Type[E]: + """The exception class.""" + assert ( + self._excinfo is not None + ), ".type can only be used after the context manager exits" + return self._excinfo[0] + + @property + def value(self) -> E: + """The exception value.""" + assert ( + self._excinfo is not None + ), ".value can only be used after the context manager exits" + return self._excinfo[1] + + @property + def tb(self) -> TracebackType: + """The exception raw traceback.""" + assert ( + self._excinfo is not None + ), ".tb can only be used after the context manager exits" + return self._excinfo[2] + + @property + def typename(self) -> str: + """The type name of the exception.""" + assert ( + self._excinfo is not None + ), ".typename can only be used after the context manager exits" + return self.type.__name__ + + @property + def traceback(self) -> Traceback: + """The traceback.""" + if self._traceback is None: + self._traceback = Traceback(self.tb) + return self._traceback + + @traceback.setter + def traceback(self, value: Traceback) -> None: + self._traceback = value + + def __repr__(self) -> str: + if self._excinfo is None: + return "" + return "<{} {} tblen={}>".format( + self.__class__.__name__, saferepr(self._excinfo[1]), len(self.traceback) + ) + + def exconly(self, tryshort: bool = False) -> str: + """Return the exception as a string. + + When 'tryshort' resolves to True, and the exception is an + AssertionError, only the actual exception part of the exception + representation is returned (so 'AssertionError: ' is removed from + the beginning). + """ + lines = format_exception_only(self.type, self.value) + text = "".join(lines) + text = text.rstrip() + if tryshort: + if text.startswith(self._striptext): + text = text[len(self._striptext) :] + return text + + def errisinstance( + self, exc: Union[Type[BaseException], Tuple[Type[BaseException], ...]] + ) -> bool: + """Return True if the exception is an instance of exc. + + Consider using ``isinstance(excinfo.value, exc)`` instead. + """ + return isinstance(self.value, exc) + + def _getreprcrash(self) -> Optional["ReprFileLocation"]: + # Find last non-hidden traceback entry that led to the exception of the + # traceback, or None if all hidden. + for i in range(-1, -len(self.traceback) - 1, -1): + entry = self.traceback[i] + if not entry.ishidden(self): + path, lineno = entry.frame.code.raw.co_filename, entry.lineno + exconly = self.exconly(tryshort=True) + return ReprFileLocation(path, lineno + 1, exconly) + return None + + def getrepr( + self, + showlocals: bool = False, + style: "_TracebackStyle" = "long", + abspath: bool = False, + tbfilter: Union[ + bool, Callable[["ExceptionInfo[BaseException]"], Traceback] + ] = True, + funcargs: bool = False, + truncate_locals: bool = True, + chain: bool = True, + ) -> Union["ReprExceptionInfo", "ExceptionChainRepr"]: + """Return str()able representation of this exception info. + + :param bool showlocals: + Show locals per traceback entry. + Ignored if ``style=="native"``. + + :param str style: + long|short|line|no|native|value traceback style. + + :param bool abspath: + If paths should be changed to absolute or left unchanged. + + :param tbfilter: + A filter for traceback entries. + + * If false, don't hide any entries. + * If true, hide internal entries and entries that contain a local + variable ``__tracebackhide__ = True``. + * If a callable, delegates the filtering to the callable. + + Ignored if ``style`` is ``"native"``. + + :param bool funcargs: + Show fixtures ("funcargs" for legacy purposes) per traceback entry. + + :param bool truncate_locals: + With ``showlocals==True``, make sure locals can be safely represented as strings. + + :param bool chain: + If chained exceptions in Python 3 should be shown. + + .. versionchanged:: 3.9 + + Added the ``chain`` parameter. + """ + if style == "native": + return ReprExceptionInfo( + reprtraceback=ReprTracebackNative( + traceback.format_exception( + self.type, + self.value, + self.traceback[0]._rawentry if self.traceback else None, + ) + ), + reprcrash=self._getreprcrash(), + ) + + fmt = FormattedExcinfo( + showlocals=showlocals, + style=style, + abspath=abspath, + tbfilter=tbfilter, + funcargs=funcargs, + truncate_locals=truncate_locals, + chain=chain, + ) + return fmt.repr_excinfo(self) + + def match(self, regexp: Union[str, Pattern[str]]) -> "Literal[True]": + """Check whether the regular expression `regexp` matches the string + representation of the exception using :func:`python:re.search`. + + If it matches `True` is returned, otherwise an `AssertionError` is raised. + """ + __tracebackhide__ = True + value = str(self.value) + msg = f"Regex pattern did not match.\n Regex: {regexp!r}\n Input: {value!r}" + if regexp == value: + msg += "\n Did you mean to `re.escape()` the regex?" + assert re.search(regexp, value), msg + # Return True to allow for "assert excinfo.match()". + return True + + +@dataclasses.dataclass +class FormattedExcinfo: + """Presenting information about failing Functions and Generators.""" + + # for traceback entries + flow_marker: ClassVar = ">" + fail_marker: ClassVar = "E" + + showlocals: bool = False + style: "_TracebackStyle" = "long" + abspath: bool = True + tbfilter: Union[bool, Callable[[ExceptionInfo[BaseException]], Traceback]] = True + funcargs: bool = False + truncate_locals: bool = True + chain: bool = True + astcache: Dict[Union[str, Path], ast.AST] = dataclasses.field( + default_factory=dict, init=False, repr=False + ) + + def _getindent(self, source: "Source") -> int: + # Figure out indent for the given source. + try: + s = str(source.getstatement(len(source) - 1)) + except KeyboardInterrupt: + raise + except BaseException: + try: + s = str(source[-1]) + except KeyboardInterrupt: + raise + except BaseException: + return 0 + return 4 + (len(s) - len(s.lstrip())) + + def _getentrysource(self, entry: TracebackEntry) -> Optional["Source"]: + source = entry.getsource(self.astcache) + if source is not None: + source = source.deindent() + return source + + def repr_args(self, entry: TracebackEntry) -> Optional["ReprFuncArgs"]: + if self.funcargs: + args = [] + for argname, argvalue in entry.frame.getargs(var=True): + args.append((argname, saferepr(argvalue))) + return ReprFuncArgs(args) + return None + + def get_source( + self, + source: Optional["Source"], + line_index: int = -1, + excinfo: Optional[ExceptionInfo[BaseException]] = None, + short: bool = False, + ) -> List[str]: + """Return formatted and marked up source lines.""" + lines = [] + if source is not None and line_index < 0: + line_index += len(source) + if source is None or line_index >= len(source.lines) or line_index < 0: + # `line_index` could still be outside `range(len(source.lines))` if + # we're processing AST with pathological position attributes. + source = Source("???") + line_index = 0 + space_prefix = " " + if short: + lines.append(space_prefix + source.lines[line_index].strip()) + else: + for line in source.lines[:line_index]: + lines.append(space_prefix + line) + lines.append(self.flow_marker + " " + source.lines[line_index]) + for line in source.lines[line_index + 1 :]: + lines.append(space_prefix + line) + if excinfo is not None: + indent = 4 if short else self._getindent(source) + lines.extend(self.get_exconly(excinfo, indent=indent, markall=True)) + return lines + + def get_exconly( + self, + excinfo: ExceptionInfo[BaseException], + indent: int = 4, + markall: bool = False, + ) -> List[str]: + lines = [] + indentstr = " " * indent + # Get the real exception information out. + exlines = excinfo.exconly(tryshort=True).split("\n") + failindent = self.fail_marker + indentstr[1:] + for line in exlines: + lines.append(failindent + line) + if not markall: + failindent = indentstr + return lines + + def repr_locals(self, locals: Mapping[str, object]) -> Optional["ReprLocals"]: + if self.showlocals: + lines = [] + keys = [loc for loc in locals if loc[0] != "@"] + keys.sort() + for name in keys: + value = locals[name] + if name == "__builtins__": + lines.append("__builtins__ = ") + else: + # This formatting could all be handled by the + # _repr() function, which is only reprlib.Repr in + # disguise, so is very configurable. + if self.truncate_locals: + str_repr = saferepr(value) + else: + str_repr = safeformat(value) + # if len(str_repr) < 70 or not isinstance(value, (list, tuple, dict)): + lines.append(f"{name:<10} = {str_repr}") + # else: + # self._line("%-10s =\\" % (name,)) + # # XXX + # pprint.pprint(value, stream=self.excinfowriter) + return ReprLocals(lines) + return None + + def repr_traceback_entry( + self, + entry: Optional[TracebackEntry], + excinfo: Optional[ExceptionInfo[BaseException]] = None, + ) -> "ReprEntry": + lines: List[str] = [] + style = ( + entry._repr_style + if entry is not None and entry._repr_style is not None + else self.style + ) + if style in ("short", "long") and entry is not None: + source = self._getentrysource(entry) + if source is None: + source = Source("???") + line_index = 0 + else: + line_index = entry.lineno - entry.getfirstlinesource() + short = style == "short" + reprargs = self.repr_args(entry) if not short else None + s = self.get_source(source, line_index, excinfo, short=short) + lines.extend(s) + if short: + message = "in %s" % (entry.name) + else: + message = excinfo and excinfo.typename or "" + entry_path = entry.path + path = self._makepath(entry_path) + reprfileloc = ReprFileLocation(path, entry.lineno + 1, message) + localsrepr = self.repr_locals(entry.locals) + return ReprEntry(lines, reprargs, localsrepr, reprfileloc, style) + elif style == "value": + if excinfo: + lines.extend(str(excinfo.value).split("\n")) + return ReprEntry(lines, None, None, None, style) + else: + if excinfo: + lines.extend(self.get_exconly(excinfo, indent=4)) + return ReprEntry(lines, None, None, None, style) + + def _makepath(self, path: Union[Path, str]) -> str: + if not self.abspath and isinstance(path, Path): + try: + np = bestrelpath(Path.cwd(), path) + except OSError: + return str(path) + if len(np) < len(str(path)): + return np + return str(path) + + def repr_traceback(self, excinfo: ExceptionInfo[BaseException]) -> "ReprTraceback": + traceback = excinfo.traceback + if callable(self.tbfilter): + traceback = self.tbfilter(excinfo) + elif self.tbfilter: + traceback = traceback.filter(excinfo) + + if isinstance(excinfo.value, RecursionError): + traceback, extraline = self._truncate_recursive_traceback(traceback) + else: + extraline = None + + if not traceback: + if extraline is None: + extraline = "All traceback entries are hidden. Pass `--full-trace` to see hidden and internal frames." + entries = [self.repr_traceback_entry(None, excinfo)] + return ReprTraceback(entries, extraline, style=self.style) + + last = traceback[-1] + if self.style == "value": + entries = [self.repr_traceback_entry(last, excinfo)] + return ReprTraceback(entries, None, style=self.style) + + entries = [ + self.repr_traceback_entry(entry, excinfo if last == entry else None) + for entry in traceback + ] + return ReprTraceback(entries, extraline, style=self.style) + + def _truncate_recursive_traceback( + self, traceback: Traceback + ) -> Tuple[Traceback, Optional[str]]: + """Truncate the given recursive traceback trying to find the starting + point of the recursion. + + The detection is done by going through each traceback entry and + finding the point in which the locals of the frame are equal to the + locals of a previous frame (see ``recursionindex()``). + + Handle the situation where the recursion process might raise an + exception (for example comparing numpy arrays using equality raises a + TypeError), in which case we do our best to warn the user of the + error and show a limited traceback. + """ + try: + recursionindex = traceback.recursionindex() + except Exception as e: + max_frames = 10 + extraline: Optional[str] = ( + "!!! Recursion error detected, but an error occurred locating the origin of recursion.\n" + " The following exception happened when comparing locals in the stack frame:\n" + " {exc_type}: {exc_msg}\n" + " Displaying first and last {max_frames} stack frames out of {total}." + ).format( + exc_type=type(e).__name__, + exc_msg=str(e), + max_frames=max_frames, + total=len(traceback), + ) + # Type ignored because adding two instances of a List subtype + # currently incorrectly has type List instead of the subtype. + traceback = traceback[:max_frames] + traceback[-max_frames:] # type: ignore + else: + if recursionindex is not None: + extraline = "!!! Recursion detected (same locals & position)" + traceback = traceback[: recursionindex + 1] + else: + extraline = None + + return traceback, extraline + + def repr_excinfo( + self, excinfo: ExceptionInfo[BaseException] + ) -> "ExceptionChainRepr": + repr_chain: List[ + Tuple[ReprTraceback, Optional[ReprFileLocation], Optional[str]] + ] = [] + e: Optional[BaseException] = excinfo.value + excinfo_: Optional[ExceptionInfo[BaseException]] = excinfo + descr = None + seen: Set[int] = set() + while e is not None and id(e) not in seen: + seen.add(id(e)) + + if excinfo_: + # Fall back to native traceback as a temporary workaround until + # full support for exception groups added to ExceptionInfo. + # See https://github.com/pytest-dev/pytest/issues/9159 + if isinstance(e, BaseExceptionGroup): + reprtraceback: Union[ + ReprTracebackNative, ReprTraceback + ] = ReprTracebackNative( + traceback.format_exception( + type(excinfo_.value), + excinfo_.value, + excinfo_.traceback[0]._rawentry, + ) + ) + else: + reprtraceback = self.repr_traceback(excinfo_) + reprcrash = excinfo_._getreprcrash() + else: + # Fallback to native repr if the exception doesn't have a traceback: + # ExceptionInfo objects require a full traceback to work. + reprtraceback = ReprTracebackNative( + traceback.format_exception(type(e), e, None) + ) + reprcrash = None + repr_chain += [(reprtraceback, reprcrash, descr)] + + if e.__cause__ is not None and self.chain: + e = e.__cause__ + excinfo_ = ExceptionInfo.from_exception(e) if e.__traceback__ else None + descr = "The above exception was the direct cause of the following exception:" + elif ( + e.__context__ is not None and not e.__suppress_context__ and self.chain + ): + e = e.__context__ + excinfo_ = ExceptionInfo.from_exception(e) if e.__traceback__ else None + descr = "During handling of the above exception, another exception occurred:" + else: + e = None + repr_chain.reverse() + return ExceptionChainRepr(repr_chain) + + +@dataclasses.dataclass(eq=False) +class TerminalRepr: + def __str__(self) -> str: + # FYI this is called from pytest-xdist's serialization of exception + # information. + io = StringIO() + tw = TerminalWriter(file=io) + self.toterminal(tw) + return io.getvalue().strip() + + def __repr__(self) -> str: + return f"<{self.__class__} instance at {id(self):0x}>" + + def toterminal(self, tw: TerminalWriter) -> None: + raise NotImplementedError() + + +# This class is abstract -- only subclasses are instantiated. +@dataclasses.dataclass(eq=False) +class ExceptionRepr(TerminalRepr): + # Provided by subclasses. + reprtraceback: "ReprTraceback" + reprcrash: Optional["ReprFileLocation"] + sections: List[Tuple[str, str, str]] = dataclasses.field( + init=False, default_factory=list + ) + + def addsection(self, name: str, content: str, sep: str = "-") -> None: + self.sections.append((name, content, sep)) + + def toterminal(self, tw: TerminalWriter) -> None: + for name, content, sep in self.sections: + tw.sep(sep, name) + tw.line(content) + + +@dataclasses.dataclass(eq=False) +class ExceptionChainRepr(ExceptionRepr): + chain: Sequence[Tuple["ReprTraceback", Optional["ReprFileLocation"], Optional[str]]] + + def __init__( + self, + chain: Sequence[ + Tuple["ReprTraceback", Optional["ReprFileLocation"], Optional[str]] + ], + ) -> None: + # reprcrash and reprtraceback of the outermost (the newest) exception + # in the chain. + super().__init__( + reprtraceback=chain[-1][0], + reprcrash=chain[-1][1], + ) + self.chain = chain + + def toterminal(self, tw: TerminalWriter) -> None: + for element in self.chain: + element[0].toterminal(tw) + if element[2] is not None: + tw.line("") + tw.line(element[2], yellow=True) + super().toterminal(tw) + + +@dataclasses.dataclass(eq=False) +class ReprExceptionInfo(ExceptionRepr): + reprtraceback: "ReprTraceback" + reprcrash: Optional["ReprFileLocation"] + + def toterminal(self, tw: TerminalWriter) -> None: + self.reprtraceback.toterminal(tw) + super().toterminal(tw) + + +@dataclasses.dataclass(eq=False) +class ReprTraceback(TerminalRepr): + reprentries: Sequence[Union["ReprEntry", "ReprEntryNative"]] + extraline: Optional[str] + style: "_TracebackStyle" + + entrysep: ClassVar = "_ " + + def toterminal(self, tw: TerminalWriter) -> None: + # The entries might have different styles. + for i, entry in enumerate(self.reprentries): + if entry.style == "long": + tw.line("") + entry.toterminal(tw) + if i < len(self.reprentries) - 1: + next_entry = self.reprentries[i + 1] + if ( + entry.style == "long" + or entry.style == "short" + and next_entry.style == "long" + ): + tw.sep(self.entrysep) + + if self.extraline: + tw.line(self.extraline) + + +class ReprTracebackNative(ReprTraceback): + def __init__(self, tblines: Sequence[str]) -> None: + self.reprentries = [ReprEntryNative(tblines)] + self.extraline = None + self.style = "native" + + +@dataclasses.dataclass(eq=False) +class ReprEntryNative(TerminalRepr): + lines: Sequence[str] + + style: ClassVar["_TracebackStyle"] = "native" + + def toterminal(self, tw: TerminalWriter) -> None: + tw.write("".join(self.lines)) + + +@dataclasses.dataclass(eq=False) +class ReprEntry(TerminalRepr): + lines: Sequence[str] + reprfuncargs: Optional["ReprFuncArgs"] + reprlocals: Optional["ReprLocals"] + reprfileloc: Optional["ReprFileLocation"] + style: "_TracebackStyle" + + def _write_entry_lines(self, tw: TerminalWriter) -> None: + """Write the source code portions of a list of traceback entries with syntax highlighting. + + Usually entries are lines like these: + + " x = 1" + "> assert x == 2" + "E assert 1 == 2" + + This function takes care of rendering the "source" portions of it (the lines without + the "E" prefix) using syntax highlighting, taking care to not highlighting the ">" + character, as doing so might break line continuations. + """ + + if not self.lines: + return + + # separate indents and source lines that are not failures: we want to + # highlight the code but not the indentation, which may contain markers + # such as "> assert 0" + fail_marker = f"{FormattedExcinfo.fail_marker} " + indent_size = len(fail_marker) + indents: List[str] = [] + source_lines: List[str] = [] + failure_lines: List[str] = [] + for index, line in enumerate(self.lines): + is_failure_line = line.startswith(fail_marker) + if is_failure_line: + # from this point on all lines are considered part of the failure + failure_lines.extend(self.lines[index:]) + break + else: + if self.style == "value": + source_lines.append(line) + else: + indents.append(line[:indent_size]) + source_lines.append(line[indent_size:]) + + tw._write_source(source_lines, indents) + + # failure lines are always completely red and bold + for line in failure_lines: + tw.line(line, bold=True, red=True) + + def toterminal(self, tw: TerminalWriter) -> None: + if self.style == "short": + if self.reprfileloc: + self.reprfileloc.toterminal(tw) + self._write_entry_lines(tw) + if self.reprlocals: + self.reprlocals.toterminal(tw, indent=" " * 8) + return + + if self.reprfuncargs: + self.reprfuncargs.toterminal(tw) + + self._write_entry_lines(tw) + + if self.reprlocals: + tw.line("") + self.reprlocals.toterminal(tw) + if self.reprfileloc: + if self.lines: + tw.line("") + self.reprfileloc.toterminal(tw) + + def __str__(self) -> str: + return "{}\n{}\n{}".format( + "\n".join(self.lines), self.reprlocals, self.reprfileloc + ) + + +@dataclasses.dataclass(eq=False) +class ReprFileLocation(TerminalRepr): + path: str + lineno: int + message: str + + def __post_init__(self) -> None: + self.path = str(self.path) + + def toterminal(self, tw: TerminalWriter) -> None: + # Filename and lineno output for each entry, using an output format + # that most editors understand. + msg = self.message + i = msg.find("\n") + if i != -1: + msg = msg[:i] + tw.write(self.path, bold=True, red=True) + tw.line(f":{self.lineno}: {msg}") + + +@dataclasses.dataclass(eq=False) +class ReprLocals(TerminalRepr): + lines: Sequence[str] + + def toterminal(self, tw: TerminalWriter, indent="") -> None: + for line in self.lines: + tw.line(indent + line) + + +@dataclasses.dataclass(eq=False) +class ReprFuncArgs(TerminalRepr): + args: Sequence[Tuple[str, object]] + + def toterminal(self, tw: TerminalWriter) -> None: + if self.args: + linesofar = "" + for name, value in self.args: + ns = f"{name} = {value}" + if len(ns) + len(linesofar) + 2 > tw.fullwidth: + if linesofar: + tw.line(linesofar) + linesofar = ns + else: + if linesofar: + linesofar += ", " + ns + else: + linesofar = ns + if linesofar: + tw.line(linesofar) + tw.line("") + + +def getfslineno(obj: object) -> Tuple[Union[str, Path], int]: + """Return source location (path, lineno) for the given object. + + If the source cannot be determined return ("", -1). + + The line number is 0-based. + """ + # xxx let decorators etc specify a sane ordering + # NOTE: this used to be done in _pytest.compat.getfslineno, initially added + # in 6ec13a2b9. It ("place_as") appears to be something very custom. + obj = get_real_func(obj) + if hasattr(obj, "place_as"): + obj = obj.place_as # type: ignore[attr-defined] + + try: + code = Code.from_function(obj) + except TypeError: + try: + fn = inspect.getsourcefile(obj) or inspect.getfile(obj) # type: ignore[arg-type] + except TypeError: + return "", -1 + + fspath = fn and absolutepath(fn) or "" + lineno = -1 + if fspath: + try: + _, lineno = findsource(obj) + except OSError: + pass + return fspath, lineno + + return code.path, code.firstlineno + + +# Relative paths that we use to filter traceback entries from appearing to the user; +# see filter_traceback. +# note: if we need to add more paths than what we have now we should probably use a list +# for better maintenance. + +_PLUGGY_DIR = Path(pluggy.__file__.rstrip("oc")) +# pluggy is either a package or a single module depending on the version +if _PLUGGY_DIR.name == "__init__.py": + _PLUGGY_DIR = _PLUGGY_DIR.parent +_PYTEST_DIR = Path(_pytest.__file__).parent + + +def filter_traceback(entry: TracebackEntry) -> bool: + """Return True if a TracebackEntry instance should be included in tracebacks. + + We hide traceback entries of: + + * dynamically generated code (no code to show up for it); + * internal traceback from pytest or its internal libraries, py and pluggy. + """ + # entry.path might sometimes return a str object when the entry + # points to dynamically generated code. + # See https://bitbucket.org/pytest-dev/py/issues/71. + raw_filename = entry.frame.code.raw.co_filename + is_generated = "<" in raw_filename and ">" in raw_filename + if is_generated: + return False + + # entry.path might point to a non-existing file, in which case it will + # also return a str object. See #1133. + p = Path(entry.path) + + parents = p.parents + if _PLUGGY_DIR in parents: + return False + if _PYTEST_DIR in parents: + return False + + return True diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_code/source.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_code/source.py new file mode 100644 index 0000000000000000000000000000000000000000..208cfb80037a807f81bbb70229c25990c42bb011 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_code/source.py @@ -0,0 +1,217 @@ +import ast +import inspect +import textwrap +import tokenize +import types +import warnings +from bisect import bisect_right +from typing import Iterable +from typing import Iterator +from typing import List +from typing import Optional +from typing import overload +from typing import Tuple +from typing import Union + + +class Source: + """An immutable object holding a source code fragment. + + When using Source(...), the source lines are deindented. + """ + + def __init__(self, obj: object = None) -> None: + if not obj: + self.lines: List[str] = [] + elif isinstance(obj, Source): + self.lines = obj.lines + elif isinstance(obj, (tuple, list)): + self.lines = deindent(x.rstrip("\n") for x in obj) + elif isinstance(obj, str): + self.lines = deindent(obj.split("\n")) + else: + try: + rawcode = getrawcode(obj) + src = inspect.getsource(rawcode) + except TypeError: + src = inspect.getsource(obj) # type: ignore[arg-type] + self.lines = deindent(src.split("\n")) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Source): + return NotImplemented + return self.lines == other.lines + + # Ignore type because of https://github.com/python/mypy/issues/4266. + __hash__ = None # type: ignore + + @overload + def __getitem__(self, key: int) -> str: + ... + + @overload + def __getitem__(self, key: slice) -> "Source": + ... + + def __getitem__(self, key: Union[int, slice]) -> Union[str, "Source"]: + if isinstance(key, int): + return self.lines[key] + else: + if key.step not in (None, 1): + raise IndexError("cannot slice a Source with a step") + newsource = Source() + newsource.lines = self.lines[key.start : key.stop] + return newsource + + def __iter__(self) -> Iterator[str]: + return iter(self.lines) + + def __len__(self) -> int: + return len(self.lines) + + def strip(self) -> "Source": + """Return new Source object with trailing and leading blank lines removed.""" + start, end = 0, len(self) + while start < end and not self.lines[start].strip(): + start += 1 + while end > start and not self.lines[end - 1].strip(): + end -= 1 + source = Source() + source.lines[:] = self.lines[start:end] + return source + + def indent(self, indent: str = " " * 4) -> "Source": + """Return a copy of the source object with all lines indented by the + given indent-string.""" + newsource = Source() + newsource.lines = [(indent + line) for line in self.lines] + return newsource + + def getstatement(self, lineno: int) -> "Source": + """Return Source statement which contains the given linenumber + (counted from 0).""" + start, end = self.getstatementrange(lineno) + return self[start:end] + + def getstatementrange(self, lineno: int) -> Tuple[int, int]: + """Return (start, end) tuple which spans the minimal statement region + which containing the given lineno.""" + if not (0 <= lineno < len(self)): + raise IndexError("lineno out of range") + ast, start, end = getstatementrange_ast(lineno, self) + return start, end + + def deindent(self) -> "Source": + """Return a new Source object deindented.""" + newsource = Source() + newsource.lines[:] = deindent(self.lines) + return newsource + + def __str__(self) -> str: + return "\n".join(self.lines) + + +# +# helper functions +# + + +def findsource(obj) -> Tuple[Optional[Source], int]: + try: + sourcelines, lineno = inspect.findsource(obj) + except Exception: + return None, -1 + source = Source() + source.lines = [line.rstrip() for line in sourcelines] + return source, lineno + + +def getrawcode(obj: object, trycall: bool = True) -> types.CodeType: + """Return code object for given function.""" + try: + return obj.__code__ # type: ignore[attr-defined,no-any-return] + except AttributeError: + pass + if trycall: + call = getattr(obj, "__call__", None) + if call and not isinstance(obj, type): + return getrawcode(call, trycall=False) + raise TypeError(f"could not get code object for {obj!r}") + + +def deindent(lines: Iterable[str]) -> List[str]: + return textwrap.dedent("\n".join(lines)).splitlines() + + +def get_statement_startend2(lineno: int, node: ast.AST) -> Tuple[int, Optional[int]]: + # Flatten all statements and except handlers into one lineno-list. + # AST's line numbers start indexing at 1. + values: List[int] = [] + for x in ast.walk(node): + if isinstance(x, (ast.stmt, ast.ExceptHandler)): + # Before Python 3.8, the lineno of a decorated class or function pointed at the decorator. + # Since Python 3.8, the lineno points to the class/def, so need to include the decorators. + if isinstance(x, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)): + for d in x.decorator_list: + values.append(d.lineno - 1) + values.append(x.lineno - 1) + for name in ("finalbody", "orelse"): + val: Optional[List[ast.stmt]] = getattr(x, name, None) + if val: + # Treat the finally/orelse part as its own statement. + values.append(val[0].lineno - 1 - 1) + values.sort() + insert_index = bisect_right(values, lineno) + start = values[insert_index - 1] + if insert_index >= len(values): + end = None + else: + end = values[insert_index] + return start, end + + +def getstatementrange_ast( + lineno: int, + source: Source, + assertion: bool = False, + astnode: Optional[ast.AST] = None, +) -> Tuple[ast.AST, int, int]: + if astnode is None: + content = str(source) + # See #4260: + # Don't produce duplicate warnings when compiling source to find AST. + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + astnode = ast.parse(content, "source", "exec") + + start, end = get_statement_startend2(lineno, astnode) + # We need to correct the end: + # - ast-parsing strips comments + # - there might be empty lines + # - we might have lesser indented code blocks at the end + if end is None: + end = len(source.lines) + + if end > start + 1: + # Make sure we don't span differently indented code blocks + # by using the BlockFinder helper used which inspect.getsource() uses itself. + block_finder = inspect.BlockFinder() + # If we start with an indented line, put blockfinder to "started" mode. + block_finder.started = source.lines[start][0].isspace() + it = ((x + "\n") for x in source.lines[start:end]) + try: + for tok in tokenize.generate_tokens(lambda: next(it)): + block_finder.tokeneater(*tok) + except (inspect.EndOfBlock, IndentationError): + end = block_finder.last + start + except Exception: + pass + + # The end might still point to a comment or empty line, correct it. + while end: + line = source.lines[end - 1].lstrip() + if line.startswith("#") or not line: + end -= 1 + else: + break + return astnode, start, end diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_io/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_io/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..db001e918cb30d25b0e12963cef2544f06bb929f --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_io/__init__.py @@ -0,0 +1,8 @@ +from .terminalwriter import get_terminal_width +from .terminalwriter import TerminalWriter + + +__all__ = [ + "TerminalWriter", + "get_terminal_width", +] diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_io/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_io/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aaf2a472993bbd0377e983ca51090b7fcdb5cf08 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_io/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_io/__pycache__/saferepr.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_io/__pycache__/saferepr.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10a6757a93a49e2e460e63959905f0e278988d83 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_io/__pycache__/saferepr.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_io/__pycache__/terminalwriter.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_io/__pycache__/terminalwriter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e589ba26f0ca4588f4b61df8a1e72325f5d9ed3 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_io/__pycache__/terminalwriter.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_io/__pycache__/wcwidth.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_io/__pycache__/wcwidth.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f382bb723bf291a24bf084cfdef529cce3e0e147 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_io/__pycache__/wcwidth.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_io/saferepr.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_io/saferepr.py new file mode 100644 index 0000000000000000000000000000000000000000..c701872238c19318fd211d5c1f6b4d6f76edb3ab --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_io/saferepr.py @@ -0,0 +1,180 @@ +import pprint +import reprlib +from typing import Any +from typing import Dict +from typing import IO +from typing import Optional + + +def _try_repr_or_str(obj: object) -> str: + try: + return repr(obj) + except (KeyboardInterrupt, SystemExit): + raise + except BaseException: + return f'{type(obj).__name__}("{obj}")' + + +def _format_repr_exception(exc: BaseException, obj: object) -> str: + try: + exc_info = _try_repr_or_str(exc) + except (KeyboardInterrupt, SystemExit): + raise + except BaseException as exc: + exc_info = f"unpresentable exception ({_try_repr_or_str(exc)})" + return "<[{} raised in repr()] {} object at 0x{:x}>".format( + exc_info, type(obj).__name__, id(obj) + ) + + +def _ellipsize(s: str, maxsize: int) -> str: + if len(s) > maxsize: + i = max(0, (maxsize - 3) // 2) + j = max(0, maxsize - 3 - i) + return s[:i] + "..." + s[len(s) - j :] + return s + + +class SafeRepr(reprlib.Repr): + """ + repr.Repr that limits the resulting size of repr() and includes + information on exceptions raised during the call. + """ + + def __init__(self, maxsize: Optional[int], use_ascii: bool = False) -> None: + """ + :param maxsize: + If not None, will truncate the resulting repr to that specific size, using ellipsis + somewhere in the middle to hide the extra text. + If None, will not impose any size limits on the returning repr. + """ + super().__init__() + # ``maxstring`` is used by the superclass, and needs to be an int; using a + # very large number in case maxsize is None, meaning we want to disable + # truncation. + self.maxstring = maxsize if maxsize is not None else 1_000_000_000 + self.maxsize = maxsize + self.use_ascii = use_ascii + + def repr(self, x: object) -> str: + try: + if self.use_ascii: + s = ascii(x) + else: + s = super().repr(x) + + except (KeyboardInterrupt, SystemExit): + raise + except BaseException as exc: + s = _format_repr_exception(exc, x) + if self.maxsize is not None: + s = _ellipsize(s, self.maxsize) + return s + + def repr_instance(self, x: object, level: int) -> str: + try: + s = repr(x) + except (KeyboardInterrupt, SystemExit): + raise + except BaseException as exc: + s = _format_repr_exception(exc, x) + if self.maxsize is not None: + s = _ellipsize(s, self.maxsize) + return s + + +def safeformat(obj: object) -> str: + """Return a pretty printed string for the given object. + + Failing __repr__ functions of user instances will be represented + with a short exception info. + """ + try: + return pprint.pformat(obj) + except Exception as exc: + return _format_repr_exception(exc, obj) + + +# Maximum size of overall repr of objects to display during assertion errors. +DEFAULT_REPR_MAX_SIZE = 240 + + +def saferepr( + obj: object, maxsize: Optional[int] = DEFAULT_REPR_MAX_SIZE, use_ascii: bool = False +) -> str: + """Return a size-limited safe repr-string for the given object. + + Failing __repr__ functions of user instances will be represented + with a short exception info and 'saferepr' generally takes + care to never raise exceptions itself. + + This function is a wrapper around the Repr/reprlib functionality of the + stdlib. + """ + + return SafeRepr(maxsize, use_ascii).repr(obj) + + +def saferepr_unlimited(obj: object, use_ascii: bool = True) -> str: + """Return an unlimited-size safe repr-string for the given object. + + As with saferepr, failing __repr__ functions of user instances + will be represented with a short exception info. + + This function is a wrapper around simple repr. + + Note: a cleaner solution would be to alter ``saferepr``this way + when maxsize=None, but that might affect some other code. + """ + try: + if use_ascii: + return ascii(obj) + return repr(obj) + except Exception as exc: + return _format_repr_exception(exc, obj) + + +class AlwaysDispatchingPrettyPrinter(pprint.PrettyPrinter): + """PrettyPrinter that always dispatches (regardless of width).""" + + def _format( + self, + object: object, + stream: IO[str], + indent: int, + allowance: int, + context: Dict[int, Any], + level: int, + ) -> None: + # Type ignored because _dispatch is private. + p = self._dispatch.get(type(object).__repr__, None) # type: ignore[attr-defined] + + objid = id(object) + if objid in context or p is None: + # Type ignored because _format is private. + super()._format( # type: ignore[misc] + object, + stream, + indent, + allowance, + context, + level, + ) + return + + context[objid] = 1 + p(self, object, stream, indent, allowance, context, level + 1) + del context[objid] + + +def _pformat_dispatch( + object: object, + indent: int = 1, + width: int = 80, + depth: Optional[int] = None, + *, + compact: bool = False, +) -> str: + return AlwaysDispatchingPrettyPrinter( + indent=indent, width=width, depth=depth, compact=compact + ).pformat(object) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_io/terminalwriter.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_io/terminalwriter.py new file mode 100644 index 0000000000000000000000000000000000000000..379035d858c92b405c02d13a2bd254ce131d2e5e --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_io/terminalwriter.py @@ -0,0 +1,233 @@ +"""Helper functions for writing to terminals and files.""" +import os +import shutil +import sys +from typing import Optional +from typing import Sequence +from typing import TextIO + +from .wcwidth import wcswidth +from _pytest.compat import final + + +# This code was initially copied from py 1.8.1, file _io/terminalwriter.py. + + +def get_terminal_width() -> int: + width, _ = shutil.get_terminal_size(fallback=(80, 24)) + + # The Windows get_terminal_size may be bogus, let's sanify a bit. + if width < 40: + width = 80 + + return width + + +def should_do_markup(file: TextIO) -> bool: + if os.environ.get("PY_COLORS") == "1": + return True + if os.environ.get("PY_COLORS") == "0": + return False + if "NO_COLOR" in os.environ: + return False + if "FORCE_COLOR" in os.environ: + return True + return ( + hasattr(file, "isatty") and file.isatty() and os.environ.get("TERM") != "dumb" + ) + + +@final +class TerminalWriter: + _esctable = dict( + black=30, + red=31, + green=32, + yellow=33, + blue=34, + purple=35, + cyan=36, + white=37, + Black=40, + Red=41, + Green=42, + Yellow=43, + Blue=44, + Purple=45, + Cyan=46, + White=47, + bold=1, + light=2, + blink=5, + invert=7, + ) + + def __init__(self, file: Optional[TextIO] = None) -> None: + if file is None: + file = sys.stdout + if hasattr(file, "isatty") and file.isatty() and sys.platform == "win32": + try: + import colorama + except ImportError: + pass + else: + file = colorama.AnsiToWin32(file).stream + assert file is not None + self._file = file + self.hasmarkup = should_do_markup(file) + self._current_line = "" + self._terminal_width: Optional[int] = None + self.code_highlight = True + + @property + def fullwidth(self) -> int: + if self._terminal_width is not None: + return self._terminal_width + return get_terminal_width() + + @fullwidth.setter + def fullwidth(self, value: int) -> None: + self._terminal_width = value + + @property + def width_of_current_line(self) -> int: + """Return an estimate of the width so far in the current line.""" + return wcswidth(self._current_line) + + def markup(self, text: str, **markup: bool) -> str: + for name in markup: + if name not in self._esctable: + raise ValueError(f"unknown markup: {name!r}") + if self.hasmarkup: + esc = [self._esctable[name] for name, on in markup.items() if on] + if esc: + text = "".join("\x1b[%sm" % cod for cod in esc) + text + "\x1b[0m" + return text + + def sep( + self, + sepchar: str, + title: Optional[str] = None, + fullwidth: Optional[int] = None, + **markup: bool, + ) -> None: + if fullwidth is None: + fullwidth = self.fullwidth + # The goal is to have the line be as long as possible + # under the condition that len(line) <= fullwidth. + if sys.platform == "win32": + # If we print in the last column on windows we are on a + # new line but there is no way to verify/neutralize this + # (we may not know the exact line width). + # So let's be defensive to avoid empty lines in the output. + fullwidth -= 1 + if title is not None: + # we want 2 + 2*len(fill) + len(title) <= fullwidth + # i.e. 2 + 2*len(sepchar)*N + len(title) <= fullwidth + # 2*len(sepchar)*N <= fullwidth - len(title) - 2 + # N <= (fullwidth - len(title) - 2) // (2*len(sepchar)) + N = max((fullwidth - len(title) - 2) // (2 * len(sepchar)), 1) + fill = sepchar * N + line = f"{fill} {title} {fill}" + else: + # we want len(sepchar)*N <= fullwidth + # i.e. N <= fullwidth // len(sepchar) + line = sepchar * (fullwidth // len(sepchar)) + # In some situations there is room for an extra sepchar at the right, + # in particular if we consider that with a sepchar like "_ " the + # trailing space is not important at the end of the line. + if len(line) + len(sepchar.rstrip()) <= fullwidth: + line += sepchar.rstrip() + + self.line(line, **markup) + + def write(self, msg: str, *, flush: bool = False, **markup: bool) -> None: + if msg: + current_line = msg.rsplit("\n", 1)[-1] + if "\n" in msg: + self._current_line = current_line + else: + self._current_line += current_line + + msg = self.markup(msg, **markup) + + try: + self._file.write(msg) + except UnicodeEncodeError: + # Some environments don't support printing general Unicode + # strings, due to misconfiguration or otherwise; in that case, + # print the string escaped to ASCII. + # When the Unicode situation improves we should consider + # letting the error propagate instead of masking it (see #7475 + # for one brief attempt). + msg = msg.encode("unicode-escape").decode("ascii") + self._file.write(msg) + + if flush: + self.flush() + + def line(self, s: str = "", **markup: bool) -> None: + self.write(s, **markup) + self.write("\n") + + def flush(self) -> None: + self._file.flush() + + def _write_source(self, lines: Sequence[str], indents: Sequence[str] = ()) -> None: + """Write lines of source code possibly highlighted. + + Keeping this private for now because the API is clunky. We should discuss how + to evolve the terminal writer so we can have more precise color support, for example + being able to write part of a line in one color and the rest in another, and so on. + """ + if indents and len(indents) != len(lines): + raise ValueError( + "indents size ({}) should have same size as lines ({})".format( + len(indents), len(lines) + ) + ) + if not indents: + indents = [""] * len(lines) + source = "\n".join(lines) + new_lines = self._highlight(source).splitlines() + for indent, new_line in zip(indents, new_lines): + self.line(indent + new_line) + + def _highlight(self, source: str) -> str: + """Highlight the given source code if we have markup support.""" + from _pytest.config.exceptions import UsageError + + if not self.hasmarkup or not self.code_highlight: + return source + try: + from pygments.formatters.terminal import TerminalFormatter + from pygments.lexers.python import PythonLexer + from pygments import highlight + import pygments.util + except ImportError: + return source + else: + try: + highlighted: str = highlight( + source, + PythonLexer(), + TerminalFormatter( + bg=os.getenv("PYTEST_THEME_MODE", "dark"), + style=os.getenv("PYTEST_THEME"), + ), + ) + return highlighted + except pygments.util.ClassNotFound: + raise UsageError( + "PYTEST_THEME environment variable had an invalid value: '{}'. " + "Only valid pygment styles are allowed.".format( + os.getenv("PYTEST_THEME") + ) + ) + except pygments.util.OptionError: + raise UsageError( + "PYTEST_THEME_MODE environment variable had an invalid value: '{}'. " + "The only allowed values are 'dark' and 'light'.".format( + os.getenv("PYTEST_THEME_MODE") + ) + ) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_io/wcwidth.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_io/wcwidth.py new file mode 100644 index 0000000000000000000000000000000000000000..e5c7bf4d8683ccc3866a15ddbc53d8b092d5c05d --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_io/wcwidth.py @@ -0,0 +1,55 @@ +import unicodedata +from functools import lru_cache + + +@lru_cache(100) +def wcwidth(c: str) -> int: + """Determine how many columns are needed to display a character in a terminal. + + Returns -1 if the character is not printable. + Returns 0, 1 or 2 for other characters. + """ + o = ord(c) + + # ASCII fast path. + if 0x20 <= o < 0x07F: + return 1 + + # Some Cf/Zp/Zl characters which should be zero-width. + if ( + o == 0x0000 + or 0x200B <= o <= 0x200F + or 0x2028 <= o <= 0x202E + or 0x2060 <= o <= 0x2063 + ): + return 0 + + category = unicodedata.category(c) + + # Control characters. + if category == "Cc": + return -1 + + # Combining characters with zero width. + if category in ("Me", "Mn"): + return 0 + + # Full/Wide east asian characters. + if unicodedata.east_asian_width(c) in ("F", "W"): + return 2 + + return 1 + + +def wcswidth(s: str) -> int: + """Determine how many columns are needed to display a string in a terminal. + + Returns -1 if the string contains non-printable characters. + """ + width = 0 + for c in unicodedata.normalize("NFC", s): + wc = wcwidth(c) + if wc < 0: + return -1 + width += wc + return width diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_py/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_py/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_py/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_py/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a89a270e4014f8c1c42bb40770d5de235447687 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_py/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_py/__pycache__/error.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_py/__pycache__/error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31946095f9a668e284d01a3718e83c32754b3100 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_py/__pycache__/error.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_py/__pycache__/path.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_py/__pycache__/path.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69be490af13e049274a2aa3992cd58aadc418588 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_py/__pycache__/path.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_py/error.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_py/error.py new file mode 100644 index 0000000000000000000000000000000000000000..0b8f2d535ef0e3f26671b9440d896e31f5ed7c69 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_py/error.py @@ -0,0 +1,109 @@ +"""create errno-specific classes for IO or os calls.""" +from __future__ import annotations + +import errno +import os +import sys +from typing import Callable +from typing import TYPE_CHECKING +from typing import TypeVar + +if TYPE_CHECKING: + from typing_extensions import ParamSpec + + P = ParamSpec("P") + +R = TypeVar("R") + + +class Error(EnvironmentError): + def __repr__(self) -> str: + return "{}.{} {!r}: {} ".format( + self.__class__.__module__, + self.__class__.__name__, + self.__class__.__doc__, + " ".join(map(str, self.args)), + # repr(self.args) + ) + + def __str__(self) -> str: + s = "[{}]: {}".format( + self.__class__.__doc__, + " ".join(map(str, self.args)), + ) + return s + + +_winerrnomap = { + 2: errno.ENOENT, + 3: errno.ENOENT, + 17: errno.EEXIST, + 18: errno.EXDEV, + 13: errno.EBUSY, # empty cd drive, but ENOMEDIUM seems unavailiable + 22: errno.ENOTDIR, + 20: errno.ENOTDIR, + 267: errno.ENOTDIR, + 5: errno.EACCES, # anything better? +} + + +class ErrorMaker: + """lazily provides Exception classes for each possible POSIX errno + (as defined per the 'errno' module). All such instances + subclass EnvironmentError. + """ + + _errno2class: dict[int, type[Error]] = {} + + def __getattr__(self, name: str) -> type[Error]: + if name[0] == "_": + raise AttributeError(name) + eno = getattr(errno, name) + cls = self._geterrnoclass(eno) + setattr(self, name, cls) + return cls + + def _geterrnoclass(self, eno: int) -> type[Error]: + try: + return self._errno2class[eno] + except KeyError: + clsname = errno.errorcode.get(eno, "UnknownErrno%d" % (eno,)) + errorcls = type( + clsname, + (Error,), + {"__module__": "py.error", "__doc__": os.strerror(eno)}, + ) + self._errno2class[eno] = errorcls + return errorcls + + def checked_call( + self, func: Callable[P, R], *args: P.args, **kwargs: P.kwargs + ) -> R: + """Call a function and raise an errno-exception if applicable.""" + __tracebackhide__ = True + try: + return func(*args, **kwargs) + except Error: + raise + except OSError as value: + if not hasattr(value, "errno"): + raise + errno = value.errno + if sys.platform == "win32": + try: + cls = self._geterrnoclass(_winerrnomap[errno]) + except KeyError: + raise value + else: + # we are not on Windows, or we got a proper OSError + cls = self._geterrnoclass(errno) + + raise cls(f"{func.__name__}{args!r}") + + +_error_maker = ErrorMaker() +checked_call = _error_maker.checked_call + + +def __getattr__(attr: str) -> type[Error]: + return getattr(_error_maker, attr) # type: ignore[no-any-return] diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_py/path.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_py/path.py new file mode 100644 index 0000000000000000000000000000000000000000..73a070d19a86a4d1f96a3d015c05b4d2be9e7854 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_py/path.py @@ -0,0 +1,1475 @@ +"""local path implementation.""" +from __future__ import annotations + +import atexit +import fnmatch +import importlib.util +import io +import os +import posixpath +import sys +import uuid +import warnings +from contextlib import contextmanager +from os.path import abspath +from os.path import dirname +from os.path import exists +from os.path import isabs +from os.path import isdir +from os.path import isfile +from os.path import islink +from os.path import normpath +from stat import S_ISDIR +from stat import S_ISLNK +from stat import S_ISREG +from typing import Any +from typing import Callable +from typing import cast +from typing import overload +from typing import TYPE_CHECKING + +from . import error + +if TYPE_CHECKING: + from typing import Literal + +# Moved from local.py. +iswin32 = sys.platform == "win32" or (getattr(os, "_name", False) == "nt") + + +class Checkers: + _depend_on_existence = "exists", "link", "dir", "file" + + def __init__(self, path): + self.path = path + + def dotfile(self): + return self.path.basename.startswith(".") + + def ext(self, arg): + if not arg.startswith("."): + arg = "." + arg + return self.path.ext == arg + + def basename(self, arg): + return self.path.basename == arg + + def basestarts(self, arg): + return self.path.basename.startswith(arg) + + def relto(self, arg): + return self.path.relto(arg) + + def fnmatch(self, arg): + return self.path.fnmatch(arg) + + def endswith(self, arg): + return str(self.path).endswith(arg) + + def _evaluate(self, kw): + from .._code.source import getrawcode + + for name, value in kw.items(): + invert = False + meth = None + try: + meth = getattr(self, name) + except AttributeError: + if name[:3] == "not": + invert = True + try: + meth = getattr(self, name[3:]) + except AttributeError: + pass + if meth is None: + raise TypeError(f"no {name!r} checker available for {self.path!r}") + try: + if getrawcode(meth).co_argcount > 1: + if (not meth(value)) ^ invert: + return False + else: + if bool(value) ^ bool(meth()) ^ invert: + return False + except (error.ENOENT, error.ENOTDIR, error.EBUSY): + # EBUSY feels not entirely correct, + # but its kind of necessary since ENOMEDIUM + # is not accessible in python + for name in self._depend_on_existence: + if name in kw: + if kw.get(name): + return False + name = "not" + name + if name in kw: + if not kw.get(name): + return False + return True + + _statcache: Stat + + def _stat(self) -> Stat: + try: + return self._statcache + except AttributeError: + try: + self._statcache = self.path.stat() + except error.ELOOP: + self._statcache = self.path.lstat() + return self._statcache + + def dir(self): + return S_ISDIR(self._stat().mode) + + def file(self): + return S_ISREG(self._stat().mode) + + def exists(self): + return self._stat() + + def link(self): + st = self.path.lstat() + return S_ISLNK(st.mode) + + +class NeverRaised(Exception): + pass + + +class Visitor: + def __init__(self, fil, rec, ignore, bf, sort): + if isinstance(fil, str): + fil = FNMatcher(fil) + if isinstance(rec, str): + self.rec: Callable[[LocalPath], bool] = FNMatcher(rec) + elif not hasattr(rec, "__call__") and rec: + self.rec = lambda path: True + else: + self.rec = rec + self.fil = fil + self.ignore = ignore + self.breadthfirst = bf + self.optsort = cast(Callable[[Any], Any], sorted) if sort else (lambda x: x) + + def gen(self, path): + try: + entries = path.listdir() + except self.ignore: + return + rec = self.rec + dirs = self.optsort( + [p for p in entries if p.check(dir=1) and (rec is None or rec(p))] + ) + if not self.breadthfirst: + for subdir in dirs: + for p in self.gen(subdir): + yield p + for p in self.optsort(entries): + if self.fil is None or self.fil(p): + yield p + if self.breadthfirst: + for subdir in dirs: + for p in self.gen(subdir): + yield p + + +class FNMatcher: + def __init__(self, pattern): + self.pattern = pattern + + def __call__(self, path): + pattern = self.pattern + + if ( + pattern.find(path.sep) == -1 + and iswin32 + and pattern.find(posixpath.sep) != -1 + ): + # Running on Windows, the pattern has no Windows path separators, + # and the pattern has one or more Posix path separators. Replace + # the Posix path separators with the Windows path separator. + pattern = pattern.replace(posixpath.sep, path.sep) + + if pattern.find(path.sep) == -1: + name = path.basename + else: + name = str(path) # path.strpath # XXX svn? + if not os.path.isabs(pattern): + pattern = "*" + path.sep + pattern + return fnmatch.fnmatch(name, pattern) + + +def map_as_list(func, iter): + return list(map(func, iter)) + + +class Stat: + if TYPE_CHECKING: + + @property + def size(self) -> int: + ... + + @property + def mtime(self) -> float: + ... + + def __getattr__(self, name: str) -> Any: + return getattr(self._osstatresult, "st_" + name) + + def __init__(self, path, osstatresult): + self.path = path + self._osstatresult = osstatresult + + @property + def owner(self): + if iswin32: + raise NotImplementedError("XXX win32") + import pwd + + entry = error.checked_call(pwd.getpwuid, self.uid) # type:ignore[attr-defined] + return entry[0] + + @property + def group(self): + """Return group name of file.""" + if iswin32: + raise NotImplementedError("XXX win32") + import grp + + entry = error.checked_call(grp.getgrgid, self.gid) # type:ignore[attr-defined] + return entry[0] + + def isdir(self): + return S_ISDIR(self._osstatresult.st_mode) + + def isfile(self): + return S_ISREG(self._osstatresult.st_mode) + + def islink(self): + self.path.lstat() + return S_ISLNK(self._osstatresult.st_mode) + + +def getuserid(user): + import pwd + + if not isinstance(user, int): + user = pwd.getpwnam(user)[2] # type:ignore[attr-defined] + return user + + +def getgroupid(group): + import grp + + if not isinstance(group, int): + group = grp.getgrnam(group)[2] # type:ignore[attr-defined] + return group + + +class LocalPath: + """Object oriented interface to os.path and other local filesystem + related information. + """ + + class ImportMismatchError(ImportError): + """raised on pyimport() if there is a mismatch of __file__'s""" + + sep = os.sep + + def __init__(self, path=None, expanduser=False): + """Initialize and return a local Path instance. + + Path can be relative to the current directory. + If path is None it defaults to the current working directory. + If expanduser is True, tilde-expansion is performed. + Note that Path instances always carry an absolute path. + Note also that passing in a local path object will simply return + the exact same path object. Use new() to get a new copy. + """ + if path is None: + self.strpath = error.checked_call(os.getcwd) + else: + try: + path = os.fspath(path) + except TypeError: + raise ValueError( + "can only pass None, Path instances " + "or non-empty strings to LocalPath" + ) + if expanduser: + path = os.path.expanduser(path) + self.strpath = abspath(path) + + if sys.platform != "win32": + + def chown(self, user, group, rec=0): + """Change ownership to the given user and group. + user and group may be specified by a number or + by a name. if rec is True change ownership + recursively. + """ + uid = getuserid(user) + gid = getgroupid(group) + if rec: + for x in self.visit(rec=lambda x: x.check(link=0)): + if x.check(link=0): + error.checked_call(os.chown, str(x), uid, gid) + error.checked_call(os.chown, str(self), uid, gid) + + def readlink(self) -> str: + """Return value of a symbolic link.""" + # https://github.com/python/mypy/issues/12278 + return error.checked_call(os.readlink, self.strpath) # type: ignore[arg-type,return-value] + + def mklinkto(self, oldname): + """Posix style hard link to another name.""" + error.checked_call(os.link, str(oldname), str(self)) + + def mksymlinkto(self, value, absolute=1): + """Create a symbolic link with the given value (pointing to another name).""" + if absolute: + error.checked_call(os.symlink, str(value), self.strpath) + else: + base = self.common(value) + # with posix local paths '/' is always a common base + relsource = self.__class__(value).relto(base) + reldest = self.relto(base) + n = reldest.count(self.sep) + target = self.sep.join(("..",) * n + (relsource,)) + error.checked_call(os.symlink, target, self.strpath) + + def __div__(self, other): + return self.join(os.fspath(other)) + + __truediv__ = __div__ # py3k + + @property + def basename(self): + """Basename part of path.""" + return self._getbyspec("basename")[0] + + @property + def dirname(self): + """Dirname part of path.""" + return self._getbyspec("dirname")[0] + + @property + def purebasename(self): + """Pure base name of the path.""" + return self._getbyspec("purebasename")[0] + + @property + def ext(self): + """Extension of the path (including the '.').""" + return self._getbyspec("ext")[0] + + def read_binary(self): + """Read and return a bytestring from reading the path.""" + with self.open("rb") as f: + return f.read() + + def read_text(self, encoding): + """Read and return a Unicode string from reading the path.""" + with self.open("r", encoding=encoding) as f: + return f.read() + + def read(self, mode="r"): + """Read and return a bytestring from reading the path.""" + with self.open(mode) as f: + return f.read() + + def readlines(self, cr=1): + """Read and return a list of lines from the path. if cr is False, the + newline will be removed from the end of each line.""" + mode = "r" + + if not cr: + content = self.read(mode) + return content.split("\n") + else: + f = self.open(mode) + try: + return f.readlines() + finally: + f.close() + + def load(self): + """(deprecated) return object unpickled from self.read()""" + f = self.open("rb") + try: + import pickle + + return error.checked_call(pickle.load, f) + finally: + f.close() + + def move(self, target): + """Move this path to target.""" + if target.relto(self): + raise error.EINVAL(target, "cannot move path into a subdirectory of itself") + try: + self.rename(target) + except error.EXDEV: # invalid cross-device link + self.copy(target) + self.remove() + + def fnmatch(self, pattern): + """Return true if the basename/fullname matches the glob-'pattern'. + + valid pattern characters:: + + * matches everything + ? matches any single character + [seq] matches any character in seq + [!seq] matches any char not in seq + + If the pattern contains a path-separator then the full path + is used for pattern matching and a '*' is prepended to the + pattern. + + if the pattern doesn't contain a path-separator the pattern + is only matched against the basename. + """ + return FNMatcher(pattern)(self) + + def relto(self, relpath): + """Return a string which is the relative part of the path + to the given 'relpath'. + """ + if not isinstance(relpath, (str, LocalPath)): + raise TypeError(f"{relpath!r}: not a string or path object") + strrelpath = str(relpath) + if strrelpath and strrelpath[-1] != self.sep: + strrelpath += self.sep + # assert strrelpath[-1] == self.sep + # assert strrelpath[-2] != self.sep + strself = self.strpath + if sys.platform == "win32" or getattr(os, "_name", None) == "nt": + if os.path.normcase(strself).startswith(os.path.normcase(strrelpath)): + return strself[len(strrelpath) :] + elif strself.startswith(strrelpath): + return strself[len(strrelpath) :] + return "" + + def ensure_dir(self, *args): + """Ensure the path joined with args is a directory.""" + return self.ensure(*args, **{"dir": True}) + + def bestrelpath(self, dest): + """Return a string which is a relative path from self + (assumed to be a directory) to dest such that + self.join(bestrelpath) == dest and if not such + path can be determined return dest. + """ + try: + if self == dest: + return os.curdir + base = self.common(dest) + if not base: # can be the case on windows + return str(dest) + self2base = self.relto(base) + reldest = dest.relto(base) + if self2base: + n = self2base.count(self.sep) + 1 + else: + n = 0 + lst = [os.pardir] * n + if reldest: + lst.append(reldest) + target = dest.sep.join(lst) + return target + except AttributeError: + return str(dest) + + def exists(self): + return self.check() + + def isdir(self): + return self.check(dir=1) + + def isfile(self): + return self.check(file=1) + + def parts(self, reverse=False): + """Return a root-first list of all ancestor directories + plus the path itself. + """ + current = self + lst = [self] + while 1: + last = current + current = current.dirpath() + if last == current: + break + lst.append(current) + if not reverse: + lst.reverse() + return lst + + def common(self, other): + """Return the common part shared with the other path + or None if there is no common part. + """ + last = None + for x, y in zip(self.parts(), other.parts()): + if x != y: + return last + last = x + return last + + def __add__(self, other): + """Return new path object with 'other' added to the basename""" + return self.new(basename=self.basename + str(other)) + + def visit(self, fil=None, rec=None, ignore=NeverRaised, bf=False, sort=False): + """Yields all paths below the current one + + fil is a filter (glob pattern or callable), if not matching the + path will not be yielded, defaulting to None (everything is + returned) + + rec is a filter (glob pattern or callable) that controls whether + a node is descended, defaulting to None + + ignore is an Exception class that is ignoredwhen calling dirlist() + on any of the paths (by default, all exceptions are reported) + + bf if True will cause a breadthfirst search instead of the + default depthfirst. Default: False + + sort if True will sort entries within each directory level. + """ + yield from Visitor(fil, rec, ignore, bf, sort).gen(self) + + def _sortlist(self, res, sort): + if sort: + if hasattr(sort, "__call__"): + warnings.warn( + DeprecationWarning( + "listdir(sort=callable) is deprecated and breaks on python3" + ), + stacklevel=3, + ) + res.sort(sort) + else: + res.sort() + + def __fspath__(self): + return self.strpath + + def __hash__(self): + s = self.strpath + if iswin32: + s = s.lower() + return hash(s) + + def __eq__(self, other): + s1 = os.fspath(self) + try: + s2 = os.fspath(other) + except TypeError: + return False + if iswin32: + s1 = s1.lower() + try: + s2 = s2.lower() + except AttributeError: + return False + return s1 == s2 + + def __ne__(self, other): + return not (self == other) + + def __lt__(self, other): + return os.fspath(self) < os.fspath(other) + + def __gt__(self, other): + return os.fspath(self) > os.fspath(other) + + def samefile(self, other): + """Return True if 'other' references the same file as 'self'.""" + other = os.fspath(other) + if not isabs(other): + other = abspath(other) + if self == other: + return True + if not hasattr(os.path, "samefile"): + return False + return error.checked_call(os.path.samefile, self.strpath, other) + + def remove(self, rec=1, ignore_errors=False): + """Remove a file or directory (or a directory tree if rec=1). + if ignore_errors is True, errors while removing directories will + be ignored. + """ + if self.check(dir=1, link=0): + if rec: + # force remove of readonly files on windows + if iswin32: + self.chmod(0o700, rec=1) + import shutil + + error.checked_call( + shutil.rmtree, self.strpath, ignore_errors=ignore_errors + ) + else: + error.checked_call(os.rmdir, self.strpath) + else: + if iswin32: + self.chmod(0o700) + error.checked_call(os.remove, self.strpath) + + def computehash(self, hashtype="md5", chunksize=524288): + """Return hexdigest of hashvalue for this file.""" + try: + try: + import hashlib as mod + except ImportError: + if hashtype == "sha1": + hashtype = "sha" + mod = __import__(hashtype) + hash = getattr(mod, hashtype)() + except (AttributeError, ImportError): + raise ValueError(f"Don't know how to compute {hashtype!r} hash") + f = self.open("rb") + try: + while 1: + buf = f.read(chunksize) + if not buf: + return hash.hexdigest() + hash.update(buf) + finally: + f.close() + + def new(self, **kw): + """Create a modified version of this path. + the following keyword arguments modify various path parts:: + + a:/some/path/to/a/file.ext + xx drive + xxxxxxxxxxxxxxxxx dirname + xxxxxxxx basename + xxxx purebasename + xxx ext + """ + obj = object.__new__(self.__class__) + if not kw: + obj.strpath = self.strpath + return obj + drive, dirname, basename, purebasename, ext = self._getbyspec( + "drive,dirname,basename,purebasename,ext" + ) + if "basename" in kw: + if "purebasename" in kw or "ext" in kw: + raise ValueError("invalid specification %r" % kw) + else: + pb = kw.setdefault("purebasename", purebasename) + try: + ext = kw["ext"] + except KeyError: + pass + else: + if ext and not ext.startswith("."): + ext = "." + ext + kw["basename"] = pb + ext + + if "dirname" in kw and not kw["dirname"]: + kw["dirname"] = drive + else: + kw.setdefault("dirname", dirname) + kw.setdefault("sep", self.sep) + obj.strpath = normpath("%(dirname)s%(sep)s%(basename)s" % kw) + return obj + + def _getbyspec(self, spec: str) -> list[str]: + """See new for what 'spec' can be.""" + res = [] + parts = self.strpath.split(self.sep) + + args = filter(None, spec.split(",")) + for name in args: + if name == "drive": + res.append(parts[0]) + elif name == "dirname": + res.append(self.sep.join(parts[:-1])) + else: + basename = parts[-1] + if name == "basename": + res.append(basename) + else: + i = basename.rfind(".") + if i == -1: + purebasename, ext = basename, "" + else: + purebasename, ext = basename[:i], basename[i:] + if name == "purebasename": + res.append(purebasename) + elif name == "ext": + res.append(ext) + else: + raise ValueError("invalid part specification %r" % name) + return res + + def dirpath(self, *args, **kwargs): + """Return the directory path joined with any given path arguments.""" + if not kwargs: + path = object.__new__(self.__class__) + path.strpath = dirname(self.strpath) + if args: + path = path.join(*args) + return path + return self.new(basename="").join(*args, **kwargs) + + def join(self, *args: os.PathLike[str], abs: bool = False) -> LocalPath: + """Return a new path by appending all 'args' as path + components. if abs=1 is used restart from root if any + of the args is an absolute path. + """ + sep = self.sep + strargs = [os.fspath(arg) for arg in args] + strpath = self.strpath + if abs: + newargs: list[str] = [] + for arg in reversed(strargs): + if isabs(arg): + strpath = arg + strargs = newargs + break + newargs.insert(0, arg) + # special case for when we have e.g. strpath == "/" + actual_sep = "" if strpath.endswith(sep) else sep + for arg in strargs: + arg = arg.strip(sep) + if iswin32: + # allow unix style paths even on windows. + arg = arg.strip("/") + arg = arg.replace("/", sep) + strpath = strpath + actual_sep + arg + actual_sep = sep + obj = object.__new__(self.__class__) + obj.strpath = normpath(strpath) + return obj + + def open(self, mode="r", ensure=False, encoding=None): + """Return an opened file with the given mode. + + If ensure is True, create parent directories if needed. + """ + if ensure: + self.dirpath().ensure(dir=1) + if encoding: + return error.checked_call(io.open, self.strpath, mode, encoding=encoding) + return error.checked_call(open, self.strpath, mode) + + def _fastjoin(self, name): + child = object.__new__(self.__class__) + child.strpath = self.strpath + self.sep + name + return child + + def islink(self): + return islink(self.strpath) + + def check(self, **kw): + """Check a path for existence and properties. + + Without arguments, return True if the path exists, otherwise False. + + valid checkers:: + + file=1 # is a file + file=0 # is not a file (may not even exist) + dir=1 # is a dir + link=1 # is a link + exists=1 # exists + + You can specify multiple checker definitions, for example:: + + path.check(file=1, link=1) # a link pointing to a file + """ + if not kw: + return exists(self.strpath) + if len(kw) == 1: + if "dir" in kw: + return not kw["dir"] ^ isdir(self.strpath) + if "file" in kw: + return not kw["file"] ^ isfile(self.strpath) + if not kw: + kw = {"exists": 1} + return Checkers(self)._evaluate(kw) + + _patternchars = set("*?[" + os.sep) + + def listdir(self, fil=None, sort=None): + """List directory contents, possibly filter by the given fil func + and possibly sorted. + """ + if fil is None and sort is None: + names = error.checked_call(os.listdir, self.strpath) + return map_as_list(self._fastjoin, names) + if isinstance(fil, str): + if not self._patternchars.intersection(fil): + child = self._fastjoin(fil) + if exists(child.strpath): + return [child] + return [] + fil = FNMatcher(fil) + names = error.checked_call(os.listdir, self.strpath) + res = [] + for name in names: + child = self._fastjoin(name) + if fil is None or fil(child): + res.append(child) + self._sortlist(res, sort) + return res + + def size(self) -> int: + """Return size of the underlying file object""" + return self.stat().size + + def mtime(self) -> float: + """Return last modification time of the path.""" + return self.stat().mtime + + def copy(self, target, mode=False, stat=False): + """Copy path to target. + + If mode is True, will copy copy permission from path to target. + If stat is True, copy permission, last modification + time, last access time, and flags from path to target. + """ + if self.check(file=1): + if target.check(dir=1): + target = target.join(self.basename) + assert self != target + copychunked(self, target) + if mode: + copymode(self.strpath, target.strpath) + if stat: + copystat(self, target) + else: + + def rec(p): + return p.check(link=0) + + for x in self.visit(rec=rec): + relpath = x.relto(self) + newx = target.join(relpath) + newx.dirpath().ensure(dir=1) + if x.check(link=1): + newx.mksymlinkto(x.readlink()) + continue + elif x.check(file=1): + copychunked(x, newx) + elif x.check(dir=1): + newx.ensure(dir=1) + if mode: + copymode(x.strpath, newx.strpath) + if stat: + copystat(x, newx) + + def rename(self, target): + """Rename this path to target.""" + target = os.fspath(target) + return error.checked_call(os.rename, self.strpath, target) + + def dump(self, obj, bin=1): + """Pickle object into path location""" + f = self.open("wb") + import pickle + + try: + error.checked_call(pickle.dump, obj, f, bin) + finally: + f.close() + + def mkdir(self, *args): + """Create & return the directory joined with args.""" + p = self.join(*args) + error.checked_call(os.mkdir, os.fspath(p)) + return p + + def write_binary(self, data, ensure=False): + """Write binary data into path. If ensure is True create + missing parent directories. + """ + if ensure: + self.dirpath().ensure(dir=1) + with self.open("wb") as f: + f.write(data) + + def write_text(self, data, encoding, ensure=False): + """Write text data into path using the specified encoding. + If ensure is True create missing parent directories. + """ + if ensure: + self.dirpath().ensure(dir=1) + with self.open("w", encoding=encoding) as f: + f.write(data) + + def write(self, data, mode="w", ensure=False): + """Write data into path. If ensure is True create + missing parent directories. + """ + if ensure: + self.dirpath().ensure(dir=1) + if "b" in mode: + if not isinstance(data, bytes): + raise ValueError("can only process bytes") + else: + if not isinstance(data, str): + if not isinstance(data, bytes): + data = str(data) + else: + data = data.decode(sys.getdefaultencoding()) + f = self.open(mode) + try: + f.write(data) + finally: + f.close() + + def _ensuredirs(self): + parent = self.dirpath() + if parent == self: + return self + if parent.check(dir=0): + parent._ensuredirs() + if self.check(dir=0): + try: + self.mkdir() + except error.EEXIST: + # race condition: file/dir created by another thread/process. + # complain if it is not a dir + if self.check(dir=0): + raise + return self + + def ensure(self, *args, **kwargs): + """Ensure that an args-joined path exists (by default as + a file). if you specify a keyword argument 'dir=True' + then the path is forced to be a directory path. + """ + p = self.join(*args) + if kwargs.get("dir", 0): + return p._ensuredirs() + else: + p.dirpath()._ensuredirs() + if not p.check(file=1): + p.open("wb").close() + return p + + @overload + def stat(self, raising: Literal[True] = ...) -> Stat: + ... + + @overload + def stat(self, raising: Literal[False]) -> Stat | None: + ... + + def stat(self, raising: bool = True) -> Stat | None: + """Return an os.stat() tuple.""" + if raising: + return Stat(self, error.checked_call(os.stat, self.strpath)) + try: + return Stat(self, os.stat(self.strpath)) + except KeyboardInterrupt: + raise + except Exception: + return None + + def lstat(self) -> Stat: + """Return an os.lstat() tuple.""" + return Stat(self, error.checked_call(os.lstat, self.strpath)) + + def setmtime(self, mtime=None): + """Set modification time for the given path. if 'mtime' is None + (the default) then the file's mtime is set to current time. + + Note that the resolution for 'mtime' is platform dependent. + """ + if mtime is None: + return error.checked_call(os.utime, self.strpath, mtime) + try: + return error.checked_call(os.utime, self.strpath, (-1, mtime)) + except error.EINVAL: + return error.checked_call(os.utime, self.strpath, (self.atime(), mtime)) + + def chdir(self): + """Change directory to self and return old current directory""" + try: + old = self.__class__() + except error.ENOENT: + old = None + error.checked_call(os.chdir, self.strpath) + return old + + @contextmanager + def as_cwd(self): + """ + Return a context manager, which changes to the path's dir during the + managed "with" context. + On __enter__ it returns the old dir, which might be ``None``. + """ + old = self.chdir() + try: + yield old + finally: + if old is not None: + old.chdir() + + def realpath(self): + """Return a new path which contains no symbolic links.""" + return self.__class__(os.path.realpath(self.strpath)) + + def atime(self): + """Return last access time of the path.""" + return self.stat().atime + + def __repr__(self): + return "local(%r)" % self.strpath + + def __str__(self): + """Return string representation of the Path.""" + return self.strpath + + def chmod(self, mode, rec=0): + """Change permissions to the given mode. If mode is an + integer it directly encodes the os-specific modes. + if rec is True perform recursively. + """ + if not isinstance(mode, int): + raise TypeError(f"mode {mode!r} must be an integer") + if rec: + for x in self.visit(rec=rec): + error.checked_call(os.chmod, str(x), mode) + error.checked_call(os.chmod, self.strpath, mode) + + def pypkgpath(self): + """Return the Python package path by looking for the last + directory upwards which still contains an __init__.py. + Return None if a pkgpath can not be determined. + """ + pkgpath = None + for parent in self.parts(reverse=True): + if parent.isdir(): + if not parent.join("__init__.py").exists(): + break + if not isimportable(parent.basename): + break + pkgpath = parent + return pkgpath + + def _ensuresyspath(self, ensuremode, path): + if ensuremode: + s = str(path) + if ensuremode == "append": + if s not in sys.path: + sys.path.append(s) + else: + if s != sys.path[0]: + sys.path.insert(0, s) + + def pyimport(self, modname=None, ensuresyspath=True): + """Return path as an imported python module. + + If modname is None, look for the containing package + and construct an according module name. + The module will be put/looked up in sys.modules. + if ensuresyspath is True then the root dir for importing + the file (taking __init__.py files into account) will + be prepended to sys.path if it isn't there already. + If ensuresyspath=="append" the root dir will be appended + if it isn't already contained in sys.path. + if ensuresyspath is False no modification of syspath happens. + + Special value of ensuresyspath=="importlib" is intended + purely for using in pytest, it is capable only of importing + separate .py files outside packages, e.g. for test suite + without any __init__.py file. It effectively allows having + same-named test modules in different places and offers + mild opt-in via this option. Note that it works only in + recent versions of python. + """ + if not self.check(): + raise error.ENOENT(self) + + if ensuresyspath == "importlib": + if modname is None: + modname = self.purebasename + spec = importlib.util.spec_from_file_location(modname, str(self)) + if spec is None or spec.loader is None: + raise ImportError( + f"Can't find module {modname} at location {str(self)}" + ) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + pkgpath = None + if modname is None: + pkgpath = self.pypkgpath() + if pkgpath is not None: + pkgroot = pkgpath.dirpath() + names = self.new(ext="").relto(pkgroot).split(self.sep) + if names[-1] == "__init__": + names.pop() + modname = ".".join(names) + else: + pkgroot = self.dirpath() + modname = self.purebasename + + self._ensuresyspath(ensuresyspath, pkgroot) + __import__(modname) + mod = sys.modules[modname] + if self.basename == "__init__.py": + return mod # we don't check anything as we might + # be in a namespace package ... too icky to check + modfile = mod.__file__ + assert modfile is not None + if modfile[-4:] in (".pyc", ".pyo"): + modfile = modfile[:-1] + elif modfile.endswith("$py.class"): + modfile = modfile[:-9] + ".py" + if modfile.endswith(os.sep + "__init__.py"): + if self.basename != "__init__.py": + modfile = modfile[:-12] + try: + issame = self.samefile(modfile) + except error.ENOENT: + issame = False + if not issame: + ignore = os.getenv("PY_IGNORE_IMPORTMISMATCH") + if ignore != "1": + raise self.ImportMismatchError(modname, modfile, self) + return mod + else: + try: + return sys.modules[modname] + except KeyError: + # we have a custom modname, do a pseudo-import + import types + + mod = types.ModuleType(modname) + mod.__file__ = str(self) + sys.modules[modname] = mod + try: + with open(str(self), "rb") as f: + exec(f.read(), mod.__dict__) + except BaseException: + del sys.modules[modname] + raise + return mod + + def sysexec(self, *argv: os.PathLike[str], **popen_opts: Any) -> str: + """Return stdout text from executing a system child process, + where the 'self' path points to executable. + The process is directly invoked and not through a system shell. + """ + from subprocess import Popen, PIPE + + popen_opts.pop("stdout", None) + popen_opts.pop("stderr", None) + proc = Popen( + [str(self)] + [str(arg) for arg in argv], + **popen_opts, + stdout=PIPE, + stderr=PIPE, + ) + stdout: str | bytes + stdout, stderr = proc.communicate() + ret = proc.wait() + if isinstance(stdout, bytes): + stdout = stdout.decode(sys.getdefaultencoding()) + if ret != 0: + if isinstance(stderr, bytes): + stderr = stderr.decode(sys.getdefaultencoding()) + raise RuntimeError( + ret, + ret, + str(self), + stdout, + stderr, + ) + return stdout + + @classmethod + def sysfind(cls, name, checker=None, paths=None): + """Return a path object found by looking at the systems + underlying PATH specification. If the checker is not None + it will be invoked to filter matching paths. If a binary + cannot be found, None is returned + Note: This is probably not working on plain win32 systems + but may work on cygwin. + """ + if isabs(name): + p = local(name) + if p.check(file=1): + return p + else: + if paths is None: + if iswin32: + paths = os.environ["Path"].split(";") + if "" not in paths and "." not in paths: + paths.append(".") + try: + systemroot = os.environ["SYSTEMROOT"] + except KeyError: + pass + else: + paths = [ + path.replace("%SystemRoot%", systemroot) for path in paths + ] + else: + paths = os.environ["PATH"].split(":") + tryadd = [] + if iswin32: + tryadd += os.environ["PATHEXT"].split(os.pathsep) + tryadd.append("") + + for x in paths: + for addext in tryadd: + p = local(x).join(name, abs=True) + addext + try: + if p.check(file=1): + if checker: + if not checker(p): + continue + return p + except error.EACCES: + pass + return None + + @classmethod + def _gethomedir(cls): + try: + x = os.environ["HOME"] + except KeyError: + try: + x = os.environ["HOMEDRIVE"] + os.environ["HOMEPATH"] + except KeyError: + return None + return cls(x) + + # """ + # special class constructors for local filesystem paths + # """ + @classmethod + def get_temproot(cls): + """Return the system's temporary directory + (where tempfiles are usually created in) + """ + import tempfile + + return local(tempfile.gettempdir()) + + @classmethod + def mkdtemp(cls, rootdir=None): + """Return a Path object pointing to a fresh new temporary directory + (which we created ourself). + """ + import tempfile + + if rootdir is None: + rootdir = cls.get_temproot() + return cls(error.checked_call(tempfile.mkdtemp, dir=str(rootdir))) + + @classmethod + def make_numbered_dir( + cls, prefix="session-", rootdir=None, keep=3, lock_timeout=172800 + ): # two days + """Return unique directory with a number greater than the current + maximum one. The number is assumed to start directly after prefix. + if keep is true directories with a number less than (maxnum-keep) + will be removed. If .lock files are used (lock_timeout non-zero), + algorithm is multi-process safe. + """ + if rootdir is None: + rootdir = cls.get_temproot() + + nprefix = prefix.lower() + + def parse_num(path): + """Parse the number out of a path (if it matches the prefix)""" + nbasename = path.basename.lower() + if nbasename.startswith(nprefix): + try: + return int(nbasename[len(nprefix) :]) + except ValueError: + pass + + def create_lockfile(path): + """Exclusively create lockfile. Throws when failed""" + mypid = os.getpid() + lockfile = path.join(".lock") + if hasattr(lockfile, "mksymlinkto"): + lockfile.mksymlinkto(str(mypid)) + else: + fd = error.checked_call( + os.open, str(lockfile), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644 + ) + with os.fdopen(fd, "w") as f: + f.write(str(mypid)) + return lockfile + + def atexit_remove_lockfile(lockfile): + """Ensure lockfile is removed at process exit""" + mypid = os.getpid() + + def try_remove_lockfile(): + # in a fork() situation, only the last process should + # remove the .lock, otherwise the other processes run the + # risk of seeing their temporary dir disappear. For now + # we remove the .lock in the parent only (i.e. we assume + # that the children finish before the parent). + if os.getpid() != mypid: + return + try: + lockfile.remove() + except error.Error: + pass + + atexit.register(try_remove_lockfile) + + # compute the maximum number currently in use with the prefix + lastmax = None + while True: + maxnum = -1 + for path in rootdir.listdir(): + num = parse_num(path) + if num is not None: + maxnum = max(maxnum, num) + + # make the new directory + try: + udir = rootdir.mkdir(prefix + str(maxnum + 1)) + if lock_timeout: + lockfile = create_lockfile(udir) + atexit_remove_lockfile(lockfile) + except (error.EEXIST, error.ENOENT, error.EBUSY): + # race condition (1): another thread/process created the dir + # in the meantime - try again + # race condition (2): another thread/process spuriously acquired + # lock treating empty directory as candidate + # for removal - try again + # race condition (3): another thread/process tried to create the lock at + # the same time (happened in Python 3.3 on Windows) + # https://ci.appveyor.com/project/pytestbot/py/build/1.0.21/job/ffi85j4c0lqwsfwa + if lastmax == maxnum: + raise + lastmax = maxnum + continue + break + + def get_mtime(path): + """Read file modification time""" + try: + return path.lstat().mtime + except error.Error: + pass + + garbage_prefix = prefix + "garbage-" + + def is_garbage(path): + """Check if path denotes directory scheduled for removal""" + bn = path.basename + return bn.startswith(garbage_prefix) + + # prune old directories + udir_time = get_mtime(udir) + if keep and udir_time: + for path in rootdir.listdir(): + num = parse_num(path) + if num is not None and num <= (maxnum - keep): + try: + # try acquiring lock to remove directory as exclusive user + if lock_timeout: + create_lockfile(path) + except (error.EEXIST, error.ENOENT, error.EBUSY): + path_time = get_mtime(path) + if not path_time: + # assume directory doesn't exist now + continue + if abs(udir_time - path_time) < lock_timeout: + # assume directory with lockfile exists + # and lock timeout hasn't expired yet + continue + + # path dir locked for exclusive use + # and scheduled for removal to avoid another thread/process + # treating it as a new directory or removal candidate + garbage_path = rootdir.join(garbage_prefix + str(uuid.uuid4())) + try: + path.rename(garbage_path) + garbage_path.remove(rec=1) + except KeyboardInterrupt: + raise + except Exception: # this might be error.Error, WindowsError ... + pass + if is_garbage(path): + try: + path.remove(rec=1) + except KeyboardInterrupt: + raise + except Exception: # this might be error.Error, WindowsError ... + pass + + # make link... + try: + username = os.environ["USER"] # linux, et al + except KeyError: + try: + username = os.environ["USERNAME"] # windows + except KeyError: + username = "current" + + src = str(udir) + dest = src[: src.rfind("-")] + "-" + username + try: + os.unlink(dest) + except OSError: + pass + try: + os.symlink(src, dest) + except (OSError, AttributeError, NotImplementedError): + pass + + return udir + + +def copymode(src, dest): + """Copy permission from src to dst.""" + import shutil + + shutil.copymode(src, dest) + + +def copystat(src, dest): + """Copy permission, last modification time, + last access time, and flags from src to dst.""" + import shutil + + shutil.copystat(str(src), str(dest)) + + +def copychunked(src, dest): + chunksize = 524288 # half a meg of bytes + fsrc = src.open("rb") + try: + fdest = dest.open("wb") + try: + while 1: + buf = fsrc.read(chunksize) + if not buf: + break + fdest.write(buf) + finally: + fdest.close() + finally: + fsrc.close() + + +def isimportable(name): + if name and (name[0].isalpha() or name[0] == "_"): + name = name.replace("_", "") + return not name or name.isalnum() + + +local = LocalPath diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/assertion/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/assertion/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a46e58136ba771e0d0a6cf32d3ad08cddf5135e2 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/assertion/__init__.py @@ -0,0 +1,181 @@ +"""Support for presenting detailed information in failing assertions.""" +import sys +from typing import Any +from typing import Generator +from typing import List +from typing import Optional +from typing import TYPE_CHECKING + +from _pytest.assertion import rewrite +from _pytest.assertion import truncate +from _pytest.assertion import util +from _pytest.assertion.rewrite import assertstate_key +from _pytest.config import Config +from _pytest.config import hookimpl +from _pytest.config.argparsing import Parser +from _pytest.nodes import Item + +if TYPE_CHECKING: + from _pytest.main import Session + + +def pytest_addoption(parser: Parser) -> None: + group = parser.getgroup("debugconfig") + group.addoption( + "--assert", + action="store", + dest="assertmode", + choices=("rewrite", "plain"), + default="rewrite", + metavar="MODE", + help=( + "Control assertion debugging tools.\n" + "'plain' performs no assertion debugging.\n" + "'rewrite' (the default) rewrites assert statements in test modules" + " on import to provide assert expression information." + ), + ) + parser.addini( + "enable_assertion_pass_hook", + type="bool", + default=False, + help="Enables the pytest_assertion_pass hook. " + "Make sure to delete any previously generated pyc cache files.", + ) + + +def register_assert_rewrite(*names: str) -> None: + """Register one or more module names to be rewritten on import. + + This function will make sure that this module or all modules inside + the package will get their assert statements rewritten. + Thus you should make sure to call this before the module is + actually imported, usually in your __init__.py if you are a plugin + using a package. + + :param names: The module names to register. + """ + for name in names: + if not isinstance(name, str): + msg = "expected module names as *args, got {0} instead" # type: ignore[unreachable] + raise TypeError(msg.format(repr(names))) + for hook in sys.meta_path: + if isinstance(hook, rewrite.AssertionRewritingHook): + importhook = hook + break + else: + # TODO(typing): Add a protocol for mark_rewrite() and use it + # for importhook and for PytestPluginManager.rewrite_hook. + importhook = DummyRewriteHook() # type: ignore + importhook.mark_rewrite(*names) + + +class DummyRewriteHook: + """A no-op import hook for when rewriting is disabled.""" + + def mark_rewrite(self, *names: str) -> None: + pass + + +class AssertionState: + """State for the assertion plugin.""" + + def __init__(self, config: Config, mode) -> None: + self.mode = mode + self.trace = config.trace.root.get("assertion") + self.hook: Optional[rewrite.AssertionRewritingHook] = None + + +def install_importhook(config: Config) -> rewrite.AssertionRewritingHook: + """Try to install the rewrite hook, raise SystemError if it fails.""" + config.stash[assertstate_key] = AssertionState(config, "rewrite") + config.stash[assertstate_key].hook = hook = rewrite.AssertionRewritingHook(config) + sys.meta_path.insert(0, hook) + config.stash[assertstate_key].trace("installed rewrite import hook") + + def undo() -> None: + hook = config.stash[assertstate_key].hook + if hook is not None and hook in sys.meta_path: + sys.meta_path.remove(hook) + + config.add_cleanup(undo) + return hook + + +def pytest_collection(session: "Session") -> None: + # This hook is only called when test modules are collected + # so for example not in the managing process of pytest-xdist + # (which does not collect test modules). + assertstate = session.config.stash.get(assertstate_key, None) + if assertstate: + if assertstate.hook is not None: + assertstate.hook.set_session(session) + + +@hookimpl(tryfirst=True, hookwrapper=True) +def pytest_runtest_protocol(item: Item) -> Generator[None, None, None]: + """Setup the pytest_assertrepr_compare and pytest_assertion_pass hooks. + + The rewrite module will use util._reprcompare if it exists to use custom + reporting via the pytest_assertrepr_compare hook. This sets up this custom + comparison for the test. + """ + + ihook = item.ihook + + def callbinrepr(op, left: object, right: object) -> Optional[str]: + """Call the pytest_assertrepr_compare hook and prepare the result. + + This uses the first result from the hook and then ensures the + following: + * Overly verbose explanations are truncated unless configured otherwise + (eg. if running in verbose mode). + * Embedded newlines are escaped to help util.format_explanation() + later. + * If the rewrite mode is used embedded %-characters are replaced + to protect later % formatting. + + The result can be formatted by util.format_explanation() for + pretty printing. + """ + hook_result = ihook.pytest_assertrepr_compare( + config=item.config, op=op, left=left, right=right + ) + for new_expl in hook_result: + if new_expl: + new_expl = truncate.truncate_if_required(new_expl, item) + new_expl = [line.replace("\n", "\\n") for line in new_expl] + res = "\n~".join(new_expl) + if item.config.getvalue("assertmode") == "rewrite": + res = res.replace("%", "%%") + return res + return None + + saved_assert_hooks = util._reprcompare, util._assertion_pass + util._reprcompare = callbinrepr + util._config = item.config + + if ihook.pytest_assertion_pass.get_hookimpls(): + + def call_assertion_pass_hook(lineno: int, orig: str, expl: str) -> None: + ihook.pytest_assertion_pass(item=item, lineno=lineno, orig=orig, expl=expl) + + util._assertion_pass = call_assertion_pass_hook + + yield + + util._reprcompare, util._assertion_pass = saved_assert_hooks + util._config = None + + +def pytest_sessionfinish(session: "Session") -> None: + assertstate = session.config.stash.get(assertstate_key, None) + if assertstate: + if assertstate.hook is not None: + assertstate.hook.set_session(None) + + +def pytest_assertrepr_compare( + config: Config, op: str, left: Any, right: Any +) -> Optional[List[str]]: + return util.assertrepr_compare(config=config, op=op, left=left, right=right) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/assertion/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/assertion/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1971cb72c046985156d7e0622fab0241d3ab368 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/assertion/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/assertion/__pycache__/rewrite.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/assertion/__pycache__/rewrite.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51a24f98a53829e33eaa7d63db5f57ea6ae72f79 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/assertion/__pycache__/rewrite.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/assertion/__pycache__/truncate.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/assertion/__pycache__/truncate.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49c4c90557712597ad9c3a212a5d655484b61bfd Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/assertion/__pycache__/truncate.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/assertion/__pycache__/util.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/assertion/__pycache__/util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca2106976bea7086ef0f0e74b5889c3a8752a69d Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/assertion/__pycache__/util.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/assertion/rewrite.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/assertion/rewrite.py new file mode 100644 index 0000000000000000000000000000000000000000..fd23552973e8435c864782932b0a9667c6366cad --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/assertion/rewrite.py @@ -0,0 +1,1211 @@ +"""Rewrite assertion AST to produce nice error messages.""" +import ast +import errno +import functools +import importlib.abc +import importlib.machinery +import importlib.util +import io +import itertools +import marshal +import os +import struct +import sys +import tokenize +import types +from collections import defaultdict +from pathlib import Path +from pathlib import PurePath +from typing import Callable +from typing import Dict +from typing import IO +from typing import Iterable +from typing import Iterator +from typing import List +from typing import Optional +from typing import Sequence +from typing import Set +from typing import Tuple +from typing import TYPE_CHECKING +from typing import Union + +from _pytest._io.saferepr import DEFAULT_REPR_MAX_SIZE +from _pytest._io.saferepr import saferepr +from _pytest._version import version +from _pytest.assertion import util +from _pytest.assertion.util import ( # noqa: F401 + format_explanation as _format_explanation, +) +from _pytest.config import Config +from _pytest.main import Session +from _pytest.pathlib import absolutepath +from _pytest.pathlib import fnmatch_ex +from _pytest.stash import StashKey + +if TYPE_CHECKING: + from _pytest.assertion import AssertionState + +if sys.version_info >= (3, 8): + namedExpr = ast.NamedExpr + astNameConstant = ast.Constant + astStr = ast.Constant + astNum = ast.Constant +else: + namedExpr = ast.Expr + astNameConstant = ast.NameConstant + astStr = ast.Str + astNum = ast.Num + + +class Sentinel: + pass + + +assertstate_key = StashKey["AssertionState"]() + +# pytest caches rewritten pycs in pycache dirs +PYTEST_TAG = f"{sys.implementation.cache_tag}-pytest-{version}" +PYC_EXT = ".py" + (__debug__ and "c" or "o") +PYC_TAIL = "." + PYTEST_TAG + PYC_EXT + +# Special marker that denotes we have just left a scope definition +_SCOPE_END_MARKER = Sentinel() + + +class AssertionRewritingHook(importlib.abc.MetaPathFinder, importlib.abc.Loader): + """PEP302/PEP451 import hook which rewrites asserts.""" + + def __init__(self, config: Config) -> None: + self.config = config + try: + self.fnpats = config.getini("python_files") + except ValueError: + self.fnpats = ["test_*.py", "*_test.py"] + self.session: Optional[Session] = None + self._rewritten_names: Dict[str, Path] = {} + self._must_rewrite: Set[str] = set() + # flag to guard against trying to rewrite a pyc file while we are already writing another pyc file, + # which might result in infinite recursion (#3506) + self._writing_pyc = False + self._basenames_to_check_rewrite = {"conftest"} + self._marked_for_rewrite_cache: Dict[str, bool] = {} + self._session_paths_checked = False + + def set_session(self, session: Optional[Session]) -> None: + self.session = session + self._session_paths_checked = False + + # Indirection so we can mock calls to find_spec originated from the hook during testing + _find_spec = importlib.machinery.PathFinder.find_spec + + def find_spec( + self, + name: str, + path: Optional[Sequence[Union[str, bytes]]] = None, + target: Optional[types.ModuleType] = None, + ) -> Optional[importlib.machinery.ModuleSpec]: + if self._writing_pyc: + return None + state = self.config.stash[assertstate_key] + if self._early_rewrite_bailout(name, state): + return None + state.trace("find_module called for: %s" % name) + + # Type ignored because mypy is confused about the `self` binding here. + spec = self._find_spec(name, path) # type: ignore + if ( + # the import machinery could not find a file to import + spec is None + # this is a namespace package (without `__init__.py`) + # there's nothing to rewrite there + or spec.origin is None + # we can only rewrite source files + or not isinstance(spec.loader, importlib.machinery.SourceFileLoader) + # if the file doesn't exist, we can't rewrite it + or not os.path.exists(spec.origin) + ): + return None + else: + fn = spec.origin + + if not self._should_rewrite(name, fn, state): + return None + + return importlib.util.spec_from_file_location( + name, + fn, + loader=self, + submodule_search_locations=spec.submodule_search_locations, + ) + + def create_module( + self, spec: importlib.machinery.ModuleSpec + ) -> Optional[types.ModuleType]: + return None # default behaviour is fine + + def exec_module(self, module: types.ModuleType) -> None: + assert module.__spec__ is not None + assert module.__spec__.origin is not None + fn = Path(module.__spec__.origin) + state = self.config.stash[assertstate_key] + + self._rewritten_names[module.__name__] = fn + + # The requested module looks like a test file, so rewrite it. This is + # the most magical part of the process: load the source, rewrite the + # asserts, and load the rewritten source. We also cache the rewritten + # module code in a special pyc. We must be aware of the possibility of + # concurrent pytest processes rewriting and loading pycs. To avoid + # tricky race conditions, we maintain the following invariant: The + # cached pyc is always a complete, valid pyc. Operations on it must be + # atomic. POSIX's atomic rename comes in handy. + write = not sys.dont_write_bytecode + cache_dir = get_cache_dir(fn) + if write: + ok = try_makedirs(cache_dir) + if not ok: + write = False + state.trace(f"read only directory: {cache_dir}") + + cache_name = fn.name[:-3] + PYC_TAIL + pyc = cache_dir / cache_name + # Notice that even if we're in a read-only directory, I'm going + # to check for a cached pyc. This may not be optimal... + co = _read_pyc(fn, pyc, state.trace) + if co is None: + state.trace(f"rewriting {fn!r}") + source_stat, co = _rewrite_test(fn, self.config) + if write: + self._writing_pyc = True + try: + _write_pyc(state, co, source_stat, pyc) + finally: + self._writing_pyc = False + else: + state.trace(f"found cached rewritten pyc for {fn}") + exec(co, module.__dict__) + + def _early_rewrite_bailout(self, name: str, state: "AssertionState") -> bool: + """A fast way to get out of rewriting modules. + + Profiling has shown that the call to PathFinder.find_spec (inside of + the find_spec from this class) is a major slowdown, so, this method + tries to filter what we're sure won't be rewritten before getting to + it. + """ + if self.session is not None and not self._session_paths_checked: + self._session_paths_checked = True + for initial_path in self.session._initialpaths: + # Make something as c:/projects/my_project/path.py -> + # ['c:', 'projects', 'my_project', 'path.py'] + parts = str(initial_path).split(os.sep) + # add 'path' to basenames to be checked. + self._basenames_to_check_rewrite.add(os.path.splitext(parts[-1])[0]) + + # Note: conftest already by default in _basenames_to_check_rewrite. + parts = name.split(".") + if parts[-1] in self._basenames_to_check_rewrite: + return False + + # For matching the name it must be as if it was a filename. + path = PurePath(*parts).with_suffix(".py") + + for pat in self.fnpats: + # if the pattern contains subdirectories ("tests/**.py" for example) we can't bail out based + # on the name alone because we need to match against the full path + if os.path.dirname(pat): + return False + if fnmatch_ex(pat, path): + return False + + if self._is_marked_for_rewrite(name, state): + return False + + state.trace(f"early skip of rewriting module: {name}") + return True + + def _should_rewrite(self, name: str, fn: str, state: "AssertionState") -> bool: + # always rewrite conftest files + if os.path.basename(fn) == "conftest.py": + state.trace(f"rewriting conftest file: {fn!r}") + return True + + if self.session is not None: + if self.session.isinitpath(absolutepath(fn)): + state.trace(f"matched test file (was specified on cmdline): {fn!r}") + return True + + # modules not passed explicitly on the command line are only + # rewritten if they match the naming convention for test files + fn_path = PurePath(fn) + for pat in self.fnpats: + if fnmatch_ex(pat, fn_path): + state.trace(f"matched test file {fn!r}") + return True + + return self._is_marked_for_rewrite(name, state) + + def _is_marked_for_rewrite(self, name: str, state: "AssertionState") -> bool: + try: + return self._marked_for_rewrite_cache[name] + except KeyError: + for marked in self._must_rewrite: + if name == marked or name.startswith(marked + "."): + state.trace(f"matched marked file {name!r} (from {marked!r})") + self._marked_for_rewrite_cache[name] = True + return True + + self._marked_for_rewrite_cache[name] = False + return False + + def mark_rewrite(self, *names: str) -> None: + """Mark import names as needing to be rewritten. + + The named module or package as well as any nested modules will + be rewritten on import. + """ + already_imported = ( + set(names).intersection(sys.modules).difference(self._rewritten_names) + ) + for name in already_imported: + mod = sys.modules[name] + if not AssertionRewriter.is_rewrite_disabled( + mod.__doc__ or "" + ) and not isinstance(mod.__loader__, type(self)): + self._warn_already_imported(name) + self._must_rewrite.update(names) + self._marked_for_rewrite_cache.clear() + + def _warn_already_imported(self, name: str) -> None: + from _pytest.warning_types import PytestAssertRewriteWarning + + self.config.issue_config_time_warning( + PytestAssertRewriteWarning( + "Module already imported so cannot be rewritten: %s" % name + ), + stacklevel=5, + ) + + def get_data(self, pathname: Union[str, bytes]) -> bytes: + """Optional PEP302 get_data API.""" + with open(pathname, "rb") as f: + return f.read() + + if sys.version_info >= (3, 10): + if sys.version_info >= (3, 12): + from importlib.resources.abc import TraversableResources + else: + from importlib.abc import TraversableResources + + def get_resource_reader(self, name: str) -> TraversableResources: # type: ignore + if sys.version_info < (3, 11): + from importlib.readers import FileReader + else: + from importlib.resources.readers import FileReader + + return FileReader( # type:ignore[no-any-return] + types.SimpleNamespace(path=self._rewritten_names[name]) + ) + + +def _write_pyc_fp( + fp: IO[bytes], source_stat: os.stat_result, co: types.CodeType +) -> None: + # Technically, we don't have to have the same pyc format as + # (C)Python, since these "pycs" should never be seen by builtin + # import. However, there's little reason to deviate. + fp.write(importlib.util.MAGIC_NUMBER) + # https://www.python.org/dev/peps/pep-0552/ + flags = b"\x00\x00\x00\x00" + fp.write(flags) + # as of now, bytecode header expects 32-bit numbers for size and mtime (#4903) + mtime = int(source_stat.st_mtime) & 0xFFFFFFFF + size = source_stat.st_size & 0xFFFFFFFF + # " bool: + proc_pyc = f"{pyc}.{os.getpid()}" + try: + with open(proc_pyc, "wb") as fp: + _write_pyc_fp(fp, source_stat, co) + except OSError as e: + state.trace(f"error writing pyc file at {proc_pyc}: errno={e.errno}") + return False + + try: + os.replace(proc_pyc, pyc) + except OSError as e: + state.trace(f"error writing pyc file at {pyc}: {e}") + # we ignore any failure to write the cache file + # there are many reasons, permission-denied, pycache dir being a + # file etc. + return False + return True + + +def _rewrite_test(fn: Path, config: Config) -> Tuple[os.stat_result, types.CodeType]: + """Read and rewrite *fn* and return the code object.""" + stat = os.stat(fn) + source = fn.read_bytes() + strfn = str(fn) + tree = ast.parse(source, filename=strfn) + rewrite_asserts(tree, source, strfn, config) + co = compile(tree, strfn, "exec", dont_inherit=True) + return stat, co + + +def _read_pyc( + source: Path, pyc: Path, trace: Callable[[str], None] = lambda x: None +) -> Optional[types.CodeType]: + """Possibly read a pytest pyc containing rewritten code. + + Return rewritten code if successful or None if not. + """ + try: + fp = open(pyc, "rb") + except OSError: + return None + with fp: + try: + stat_result = os.stat(source) + mtime = int(stat_result.st_mtime) + size = stat_result.st_size + data = fp.read(16) + except OSError as e: + trace(f"_read_pyc({source}): OSError {e}") + return None + # Check for invalid or out of date pyc file. + if len(data) != (16): + trace("_read_pyc(%s): invalid pyc (too short)" % source) + return None + if data[:4] != importlib.util.MAGIC_NUMBER: + trace("_read_pyc(%s): invalid pyc (bad magic number)" % source) + return None + if data[4:8] != b"\x00\x00\x00\x00": + trace("_read_pyc(%s): invalid pyc (unsupported flags)" % source) + return None + mtime_data = data[8:12] + if int.from_bytes(mtime_data, "little") != mtime & 0xFFFFFFFF: + trace("_read_pyc(%s): out of date" % source) + return None + size_data = data[12:16] + if int.from_bytes(size_data, "little") != size & 0xFFFFFFFF: + trace("_read_pyc(%s): invalid pyc (incorrect size)" % source) + return None + try: + co = marshal.load(fp) + except Exception as e: + trace(f"_read_pyc({source}): marshal.load error {e}") + return None + if not isinstance(co, types.CodeType): + trace("_read_pyc(%s): not a code object" % source) + return None + return co + + +def rewrite_asserts( + mod: ast.Module, + source: bytes, + module_path: Optional[str] = None, + config: Optional[Config] = None, +) -> None: + """Rewrite the assert statements in mod.""" + AssertionRewriter(module_path, config, source).run(mod) + + +def _saferepr(obj: object) -> str: + r"""Get a safe repr of an object for assertion error messages. + + The assertion formatting (util.format_explanation()) requires + newlines to be escaped since they are a special character for it. + Normally assertion.util.format_explanation() does this but for a + custom repr it is possible to contain one of the special escape + sequences, especially '\n{' and '\n}' are likely to be present in + JSON reprs. + """ + maxsize = _get_maxsize_for_saferepr(util._config) + return saferepr(obj, maxsize=maxsize).replace("\n", "\\n") + + +def _get_maxsize_for_saferepr(config: Optional[Config]) -> Optional[int]: + """Get `maxsize` configuration for saferepr based on the given config object.""" + verbosity = config.getoption("verbose") if config is not None else 0 + if verbosity >= 2: + return None + if verbosity >= 1: + return DEFAULT_REPR_MAX_SIZE * 10 + return DEFAULT_REPR_MAX_SIZE + + +def _format_assertmsg(obj: object) -> str: + r"""Format the custom assertion message given. + + For strings this simply replaces newlines with '\n~' so that + util.format_explanation() will preserve them instead of escaping + newlines. For other objects saferepr() is used first. + """ + # reprlib appears to have a bug which means that if a string + # contains a newline it gets escaped, however if an object has a + # .__repr__() which contains newlines it does not get escaped. + # However in either case we want to preserve the newline. + replaces = [("\n", "\n~"), ("%", "%%")] + if not isinstance(obj, str): + obj = saferepr(obj) + replaces.append(("\\n", "\n~")) + + for r1, r2 in replaces: + obj = obj.replace(r1, r2) + + return obj + + +def _should_repr_global_name(obj: object) -> bool: + if callable(obj): + return False + + try: + return not hasattr(obj, "__name__") + except Exception: + return True + + +def _format_boolop(explanations: Iterable[str], is_or: bool) -> str: + explanation = "(" + (is_or and " or " or " and ").join(explanations) + ")" + return explanation.replace("%", "%%") + + +def _call_reprcompare( + ops: Sequence[str], + results: Sequence[bool], + expls: Sequence[str], + each_obj: Sequence[object], +) -> str: + for i, res, expl in zip(range(len(ops)), results, expls): + try: + done = not res + except Exception: + done = True + if done: + break + if util._reprcompare is not None: + custom = util._reprcompare(ops[i], each_obj[i], each_obj[i + 1]) + if custom is not None: + return custom + return expl + + +def _call_assertion_pass(lineno: int, orig: str, expl: str) -> None: + if util._assertion_pass is not None: + util._assertion_pass(lineno, orig, expl) + + +def _check_if_assertion_pass_impl() -> bool: + """Check if any plugins implement the pytest_assertion_pass hook + in order not to generate explanation unnecessarily (might be expensive).""" + return True if util._assertion_pass else False + + +UNARY_MAP = {ast.Not: "not %s", ast.Invert: "~%s", ast.USub: "-%s", ast.UAdd: "+%s"} + +BINOP_MAP = { + ast.BitOr: "|", + ast.BitXor: "^", + ast.BitAnd: "&", + ast.LShift: "<<", + ast.RShift: ">>", + ast.Add: "+", + ast.Sub: "-", + ast.Mult: "*", + ast.Div: "/", + ast.FloorDiv: "//", + ast.Mod: "%%", # escaped for string formatting + ast.Eq: "==", + ast.NotEq: "!=", + ast.Lt: "<", + ast.LtE: "<=", + ast.Gt: ">", + ast.GtE: ">=", + ast.Pow: "**", + ast.Is: "is", + ast.IsNot: "is not", + ast.In: "in", + ast.NotIn: "not in", + ast.MatMult: "@", +} + + +def traverse_node(node: ast.AST) -> Iterator[ast.AST]: + """Recursively yield node and all its children in depth-first order.""" + yield node + for child in ast.iter_child_nodes(node): + yield from traverse_node(child) + + +@functools.lru_cache(maxsize=1) +def _get_assertion_exprs(src: bytes) -> Dict[int, str]: + """Return a mapping from {lineno: "assertion test expression"}.""" + ret: Dict[int, str] = {} + + depth = 0 + lines: List[str] = [] + assert_lineno: Optional[int] = None + seen_lines: Set[int] = set() + + def _write_and_reset() -> None: + nonlocal depth, lines, assert_lineno, seen_lines + assert assert_lineno is not None + ret[assert_lineno] = "".join(lines).rstrip().rstrip("\\") + depth = 0 + lines = [] + assert_lineno = None + seen_lines = set() + + tokens = tokenize.tokenize(io.BytesIO(src).readline) + for tp, source, (lineno, offset), _, line in tokens: + if tp == tokenize.NAME and source == "assert": + assert_lineno = lineno + elif assert_lineno is not None: + # keep track of depth for the assert-message `,` lookup + if tp == tokenize.OP and source in "([{": + depth += 1 + elif tp == tokenize.OP and source in ")]}": + depth -= 1 + + if not lines: + lines.append(line[offset:]) + seen_lines.add(lineno) + # a non-nested comma separates the expression from the message + elif depth == 0 and tp == tokenize.OP and source == ",": + # one line assert with message + if lineno in seen_lines and len(lines) == 1: + offset_in_trimmed = offset + len(lines[-1]) - len(line) + lines[-1] = lines[-1][:offset_in_trimmed] + # multi-line assert with message + elif lineno in seen_lines: + lines[-1] = lines[-1][:offset] + # multi line assert with escapd newline before message + else: + lines.append(line[:offset]) + _write_and_reset() + elif tp in {tokenize.NEWLINE, tokenize.ENDMARKER}: + _write_and_reset() + elif lines and lineno not in seen_lines: + lines.append(line) + seen_lines.add(lineno) + + return ret + + +class AssertionRewriter(ast.NodeVisitor): + """Assertion rewriting implementation. + + The main entrypoint is to call .run() with an ast.Module instance, + this will then find all the assert statements and rewrite them to + provide intermediate values and a detailed assertion error. See + http://pybites.blogspot.be/2011/07/behind-scenes-of-pytests-new-assertion.html + for an overview of how this works. + + The entry point here is .run() which will iterate over all the + statements in an ast.Module and for each ast.Assert statement it + finds call .visit() with it. Then .visit_Assert() takes over and + is responsible for creating new ast statements to replace the + original assert statement: it rewrites the test of an assertion + to provide intermediate values and replace it with an if statement + which raises an assertion error with a detailed explanation in + case the expression is false and calls pytest_assertion_pass hook + if expression is true. + + For this .visit_Assert() uses the visitor pattern to visit all the + AST nodes of the ast.Assert.test field, each visit call returning + an AST node and the corresponding explanation string. During this + state is kept in several instance attributes: + + :statements: All the AST statements which will replace the assert + statement. + + :variables: This is populated by .variable() with each variable + used by the statements so that they can all be set to None at + the end of the statements. + + :variable_counter: Counter to create new unique variables needed + by statements. Variables are created using .variable() and + have the form of "@py_assert0". + + :expl_stmts: The AST statements which will be executed to get + data from the assertion. This is the code which will construct + the detailed assertion message that is used in the AssertionError + or for the pytest_assertion_pass hook. + + :explanation_specifiers: A dict filled by .explanation_param() + with %-formatting placeholders and their corresponding + expressions to use in the building of an assertion message. + This is used by .pop_format_context() to build a message. + + :stack: A stack of the explanation_specifiers dicts maintained by + .push_format_context() and .pop_format_context() which allows + to build another %-formatted string while already building one. + + :scope: A tuple containing the current scope used for variables_overwrite. + + :variables_overwrite: A dict filled with references to variables + that change value within an assert. This happens when a variable is + reassigned with the walrus operator + + This state, except the variables_overwrite, is reset on every new assert + statement visited and used by the other visitors. + """ + + def __init__( + self, module_path: Optional[str], config: Optional[Config], source: bytes + ) -> None: + super().__init__() + self.module_path = module_path + self.config = config + if config is not None: + self.enable_assertion_pass_hook = config.getini( + "enable_assertion_pass_hook" + ) + else: + self.enable_assertion_pass_hook = False + self.source = source + self.scope: tuple[ast.AST, ...] = () + self.variables_overwrite: defaultdict[ + tuple[ast.AST, ...], Dict[str, str] + ] = defaultdict(dict) + + def run(self, mod: ast.Module) -> None: + """Find all assert statements in *mod* and rewrite them.""" + if not mod.body: + # Nothing to do. + return + + # We'll insert some special imports at the top of the module, but after any + # docstrings and __future__ imports, so first figure out where that is. + doc = getattr(mod, "docstring", None) + expect_docstring = doc is None + if doc is not None and self.is_rewrite_disabled(doc): + return + pos = 0 + item = None + for item in mod.body: + if ( + expect_docstring + and isinstance(item, ast.Expr) + and isinstance(item.value, astStr) + ): + if sys.version_info >= (3, 8): + doc = item.value.value + else: + doc = item.value.s + if self.is_rewrite_disabled(doc): + return + expect_docstring = False + elif ( + isinstance(item, ast.ImportFrom) + and item.level == 0 + and item.module == "__future__" + ): + pass + else: + break + pos += 1 + # Special case: for a decorated function, set the lineno to that of the + # first decorator, not the `def`. Issue #4984. + if isinstance(item, ast.FunctionDef) and item.decorator_list: + lineno = item.decorator_list[0].lineno + else: + lineno = item.lineno + # Now actually insert the special imports. + if sys.version_info >= (3, 10): + aliases = [ + ast.alias("builtins", "@py_builtins", lineno=lineno, col_offset=0), + ast.alias( + "_pytest.assertion.rewrite", + "@pytest_ar", + lineno=lineno, + col_offset=0, + ), + ] + else: + aliases = [ + ast.alias("builtins", "@py_builtins"), + ast.alias("_pytest.assertion.rewrite", "@pytest_ar"), + ] + imports = [ + ast.Import([alias], lineno=lineno, col_offset=0) for alias in aliases + ] + mod.body[pos:pos] = imports + + # Collect asserts. + self.scope = (mod,) + nodes: List[Union[ast.AST, Sentinel]] = [mod] + while nodes: + node = nodes.pop() + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + self.scope = tuple((*self.scope, node)) + nodes.append(_SCOPE_END_MARKER) + if node == _SCOPE_END_MARKER: + self.scope = self.scope[:-1] + continue + assert isinstance(node, ast.AST) + for name, field in ast.iter_fields(node): + if isinstance(field, list): + new: List[ast.AST] = [] + for i, child in enumerate(field): + if isinstance(child, ast.Assert): + # Transform assert. + new.extend(self.visit(child)) + else: + new.append(child) + if isinstance(child, ast.AST): + nodes.append(child) + setattr(node, name, new) + elif ( + isinstance(field, ast.AST) + # Don't recurse into expressions as they can't contain + # asserts. + and not isinstance(field, ast.expr) + ): + nodes.append(field) + + @staticmethod + def is_rewrite_disabled(docstring: str) -> bool: + return "PYTEST_DONT_REWRITE" in docstring + + def variable(self) -> str: + """Get a new variable.""" + # Use a character invalid in python identifiers to avoid clashing. + name = "@py_assert" + str(next(self.variable_counter)) + self.variables.append(name) + return name + + def assign(self, expr: ast.expr) -> ast.Name: + """Give *expr* a name.""" + name = self.variable() + self.statements.append(ast.Assign([ast.Name(name, ast.Store())], expr)) + return ast.Name(name, ast.Load()) + + def display(self, expr: ast.expr) -> ast.expr: + """Call saferepr on the expression.""" + return self.helper("_saferepr", expr) + + def helper(self, name: str, *args: ast.expr) -> ast.expr: + """Call a helper in this module.""" + py_name = ast.Name("@pytest_ar", ast.Load()) + attr = ast.Attribute(py_name, name, ast.Load()) + return ast.Call(attr, list(args), []) + + def builtin(self, name: str) -> ast.Attribute: + """Return the builtin called *name*.""" + builtin_name = ast.Name("@py_builtins", ast.Load()) + return ast.Attribute(builtin_name, name, ast.Load()) + + def explanation_param(self, expr: ast.expr) -> str: + """Return a new named %-formatting placeholder for expr. + + This creates a %-formatting placeholder for expr in the + current formatting context, e.g. ``%(py0)s``. The placeholder + and expr are placed in the current format context so that it + can be used on the next call to .pop_format_context(). + """ + specifier = "py" + str(next(self.variable_counter)) + self.explanation_specifiers[specifier] = expr + return "%(" + specifier + ")s" + + def push_format_context(self) -> None: + """Create a new formatting context. + + The format context is used for when an explanation wants to + have a variable value formatted in the assertion message. In + this case the value required can be added using + .explanation_param(). Finally .pop_format_context() is used + to format a string of %-formatted values as added by + .explanation_param(). + """ + self.explanation_specifiers: Dict[str, ast.expr] = {} + self.stack.append(self.explanation_specifiers) + + def pop_format_context(self, expl_expr: ast.expr) -> ast.Name: + """Format the %-formatted string with current format context. + + The expl_expr should be an str ast.expr instance constructed from + the %-placeholders created by .explanation_param(). This will + add the required code to format said string to .expl_stmts and + return the ast.Name instance of the formatted string. + """ + current = self.stack.pop() + if self.stack: + self.explanation_specifiers = self.stack[-1] + keys = [astStr(key) for key in current.keys()] + format_dict = ast.Dict(keys, list(current.values())) + form = ast.BinOp(expl_expr, ast.Mod(), format_dict) + name = "@py_format" + str(next(self.variable_counter)) + if self.enable_assertion_pass_hook: + self.format_variables.append(name) + self.expl_stmts.append(ast.Assign([ast.Name(name, ast.Store())], form)) + return ast.Name(name, ast.Load()) + + def generic_visit(self, node: ast.AST) -> Tuple[ast.Name, str]: + """Handle expressions we don't have custom code for.""" + assert isinstance(node, ast.expr) + res = self.assign(node) + return res, self.explanation_param(self.display(res)) + + def visit_Assert(self, assert_: ast.Assert) -> List[ast.stmt]: + """Return the AST statements to replace the ast.Assert instance. + + This rewrites the test of an assertion to provide + intermediate values and replace it with an if statement which + raises an assertion error with a detailed explanation in case + the expression is false. + """ + if isinstance(assert_.test, ast.Tuple) and len(assert_.test.elts) >= 1: + from _pytest.warning_types import PytestAssertRewriteWarning + import warnings + + # TODO: This assert should not be needed. + assert self.module_path is not None + warnings.warn_explicit( + PytestAssertRewriteWarning( + "assertion is always true, perhaps remove parentheses?" + ), + category=None, + filename=self.module_path, + lineno=assert_.lineno, + ) + + self.statements: List[ast.stmt] = [] + self.variables: List[str] = [] + self.variable_counter = itertools.count() + + if self.enable_assertion_pass_hook: + self.format_variables: List[str] = [] + + self.stack: List[Dict[str, ast.expr]] = [] + self.expl_stmts: List[ast.stmt] = [] + self.push_format_context() + # Rewrite assert into a bunch of statements. + top_condition, explanation = self.visit(assert_.test) + + negation = ast.UnaryOp(ast.Not(), top_condition) + + if self.enable_assertion_pass_hook: # Experimental pytest_assertion_pass hook + msg = self.pop_format_context(astStr(explanation)) + + # Failed + if assert_.msg: + assertmsg = self.helper("_format_assertmsg", assert_.msg) + gluestr = "\n>assert " + else: + assertmsg = astStr("") + gluestr = "assert " + err_explanation = ast.BinOp(astStr(gluestr), ast.Add(), msg) + err_msg = ast.BinOp(assertmsg, ast.Add(), err_explanation) + err_name = ast.Name("AssertionError", ast.Load()) + fmt = self.helper("_format_explanation", err_msg) + exc = ast.Call(err_name, [fmt], []) + raise_ = ast.Raise(exc, None) + statements_fail = [] + statements_fail.extend(self.expl_stmts) + statements_fail.append(raise_) + + # Passed + fmt_pass = self.helper("_format_explanation", msg) + orig = _get_assertion_exprs(self.source)[assert_.lineno] + hook_call_pass = ast.Expr( + self.helper( + "_call_assertion_pass", + astNum(assert_.lineno), + astStr(orig), + fmt_pass, + ) + ) + # If any hooks implement assert_pass hook + hook_impl_test = ast.If( + self.helper("_check_if_assertion_pass_impl"), + self.expl_stmts + [hook_call_pass], + [], + ) + statements_pass = [hook_impl_test] + + # Test for assertion condition + main_test = ast.If(negation, statements_fail, statements_pass) + self.statements.append(main_test) + if self.format_variables: + variables = [ + ast.Name(name, ast.Store()) for name in self.format_variables + ] + clear_format = ast.Assign(variables, astNameConstant(None)) + self.statements.append(clear_format) + + else: # Original assertion rewriting + # Create failure message. + body = self.expl_stmts + self.statements.append(ast.If(negation, body, [])) + if assert_.msg: + assertmsg = self.helper("_format_assertmsg", assert_.msg) + explanation = "\n>assert " + explanation + else: + assertmsg = astStr("") + explanation = "assert " + explanation + template = ast.BinOp(assertmsg, ast.Add(), astStr(explanation)) + msg = self.pop_format_context(template) + fmt = self.helper("_format_explanation", msg) + err_name = ast.Name("AssertionError", ast.Load()) + exc = ast.Call(err_name, [fmt], []) + raise_ = ast.Raise(exc, None) + + body.append(raise_) + + # Clear temporary variables by setting them to None. + if self.variables: + variables = [ast.Name(name, ast.Store()) for name in self.variables] + clear = ast.Assign(variables, astNameConstant(None)) + self.statements.append(clear) + # Fix locations (line numbers/column offsets). + for stmt in self.statements: + for node in traverse_node(stmt): + ast.copy_location(node, assert_) + return self.statements + + def visit_NamedExpr(self, name: namedExpr) -> Tuple[namedExpr, str]: + # This method handles the 'walrus operator' repr of the target + # name if it's a local variable or _should_repr_global_name() + # thinks it's acceptable. + locs = ast.Call(self.builtin("locals"), [], []) + target_id = name.target.id # type: ignore[attr-defined] + inlocs = ast.Compare(astStr(target_id), [ast.In()], [locs]) + dorepr = self.helper("_should_repr_global_name", name) + test = ast.BoolOp(ast.Or(), [inlocs, dorepr]) + expr = ast.IfExp(test, self.display(name), astStr(target_id)) + return name, self.explanation_param(expr) + + def visit_Name(self, name: ast.Name) -> Tuple[ast.Name, str]: + # Display the repr of the name if it's a local variable or + # _should_repr_global_name() thinks it's acceptable. + locs = ast.Call(self.builtin("locals"), [], []) + inlocs = ast.Compare(astStr(name.id), [ast.In()], [locs]) + dorepr = self.helper("_should_repr_global_name", name) + test = ast.BoolOp(ast.Or(), [inlocs, dorepr]) + expr = ast.IfExp(test, self.display(name), astStr(name.id)) + return name, self.explanation_param(expr) + + def visit_BoolOp(self, boolop: ast.BoolOp) -> Tuple[ast.Name, str]: + res_var = self.variable() + expl_list = self.assign(ast.List([], ast.Load())) + app = ast.Attribute(expl_list, "append", ast.Load()) + is_or = int(isinstance(boolop.op, ast.Or)) + body = save = self.statements + fail_save = self.expl_stmts + levels = len(boolop.values) - 1 + self.push_format_context() + # Process each operand, short-circuiting if needed. + for i, v in enumerate(boolop.values): + if i: + fail_inner: List[ast.stmt] = [] + # cond is set in a prior loop iteration below + self.expl_stmts.append(ast.If(cond, fail_inner, [])) # noqa + self.expl_stmts = fail_inner + # Check if the left operand is a namedExpr and the value has already been visited + if ( + isinstance(v, ast.Compare) + and isinstance(v.left, namedExpr) + and v.left.target.id + in [ + ast_expr.id + for ast_expr in boolop.values[:i] + if hasattr(ast_expr, "id") + ] + ): + pytest_temp = self.variable() + self.variables_overwrite[self.scope][ + v.left.target.id + ] = v.left # type:ignore[assignment] + v.left.target.id = pytest_temp + self.push_format_context() + res, expl = self.visit(v) + body.append(ast.Assign([ast.Name(res_var, ast.Store())], res)) + expl_format = self.pop_format_context(astStr(expl)) + call = ast.Call(app, [expl_format], []) + self.expl_stmts.append(ast.Expr(call)) + if i < levels: + cond: ast.expr = res + if is_or: + cond = ast.UnaryOp(ast.Not(), cond) + inner: List[ast.stmt] = [] + self.statements.append(ast.If(cond, inner, [])) + self.statements = body = inner + self.statements = save + self.expl_stmts = fail_save + expl_template = self.helper("_format_boolop", expl_list, astNum(is_or)) + expl = self.pop_format_context(expl_template) + return ast.Name(res_var, ast.Load()), self.explanation_param(expl) + + def visit_UnaryOp(self, unary: ast.UnaryOp) -> Tuple[ast.Name, str]: + pattern = UNARY_MAP[unary.op.__class__] + operand_res, operand_expl = self.visit(unary.operand) + res = self.assign(ast.UnaryOp(unary.op, operand_res)) + return res, pattern % (operand_expl,) + + def visit_BinOp(self, binop: ast.BinOp) -> Tuple[ast.Name, str]: + symbol = BINOP_MAP[binop.op.__class__] + left_expr, left_expl = self.visit(binop.left) + right_expr, right_expl = self.visit(binop.right) + explanation = f"({left_expl} {symbol} {right_expl})" + res = self.assign(ast.BinOp(left_expr, binop.op, right_expr)) + return res, explanation + + def visit_Call(self, call: ast.Call) -> Tuple[ast.Name, str]: + new_func, func_expl = self.visit(call.func) + arg_expls = [] + new_args = [] + new_kwargs = [] + for arg in call.args: + if isinstance(arg, ast.Name) and arg.id in self.variables_overwrite.get( + self.scope, {} + ): + arg = self.variables_overwrite[self.scope][ + arg.id + ] # type:ignore[assignment] + res, expl = self.visit(arg) + arg_expls.append(expl) + new_args.append(res) + for keyword in call.keywords: + if isinstance( + keyword.value, ast.Name + ) and keyword.value.id in self.variables_overwrite.get(self.scope, {}): + keyword.value = self.variables_overwrite[self.scope][ + keyword.value.id + ] # type:ignore[assignment] + res, expl = self.visit(keyword.value) + new_kwargs.append(ast.keyword(keyword.arg, res)) + if keyword.arg: + arg_expls.append(keyword.arg + "=" + expl) + else: # **args have `arg` keywords with an .arg of None + arg_expls.append("**" + expl) + + expl = "{}({})".format(func_expl, ", ".join(arg_expls)) + new_call = ast.Call(new_func, new_args, new_kwargs) + res = self.assign(new_call) + res_expl = self.explanation_param(self.display(res)) + outer_expl = f"{res_expl}\n{{{res_expl} = {expl}\n}}" + return res, outer_expl + + def visit_Starred(self, starred: ast.Starred) -> Tuple[ast.Starred, str]: + # A Starred node can appear in a function call. + res, expl = self.visit(starred.value) + new_starred = ast.Starred(res, starred.ctx) + return new_starred, "*" + expl + + def visit_Attribute(self, attr: ast.Attribute) -> Tuple[ast.Name, str]: + if not isinstance(attr.ctx, ast.Load): + return self.generic_visit(attr) + value, value_expl = self.visit(attr.value) + res = self.assign(ast.Attribute(value, attr.attr, ast.Load())) + res_expl = self.explanation_param(self.display(res)) + pat = "%s\n{%s = %s.%s\n}" + expl = pat % (res_expl, res_expl, value_expl, attr.attr) + return res, expl + + def visit_Compare(self, comp: ast.Compare) -> Tuple[ast.expr, str]: + self.push_format_context() + # We first check if we have overwritten a variable in the previous assert + if isinstance( + comp.left, ast.Name + ) and comp.left.id in self.variables_overwrite.get(self.scope, {}): + comp.left = self.variables_overwrite[self.scope][ + comp.left.id + ] # type:ignore[assignment] + if isinstance(comp.left, namedExpr): + self.variables_overwrite[self.scope][ + comp.left.target.id + ] = comp.left # type:ignore[assignment] + left_res, left_expl = self.visit(comp.left) + if isinstance(comp.left, (ast.Compare, ast.BoolOp)): + left_expl = f"({left_expl})" + res_variables = [self.variable() for i in range(len(comp.ops))] + load_names = [ast.Name(v, ast.Load()) for v in res_variables] + store_names = [ast.Name(v, ast.Store()) for v in res_variables] + it = zip(range(len(comp.ops)), comp.ops, comp.comparators) + expls = [] + syms = [] + results = [left_res] + for i, op, next_operand in it: + if ( + isinstance(next_operand, namedExpr) + and isinstance(left_res, ast.Name) + and next_operand.target.id == left_res.id + ): + next_operand.target.id = self.variable() + self.variables_overwrite[self.scope][ + left_res.id + ] = next_operand # type:ignore[assignment] + next_res, next_expl = self.visit(next_operand) + if isinstance(next_operand, (ast.Compare, ast.BoolOp)): + next_expl = f"({next_expl})" + results.append(next_res) + sym = BINOP_MAP[op.__class__] + syms.append(astStr(sym)) + expl = f"{left_expl} {sym} {next_expl}" + expls.append(astStr(expl)) + res_expr = ast.Compare(left_res, [op], [next_res]) + self.statements.append(ast.Assign([store_names[i]], res_expr)) + left_res, left_expl = next_res, next_expl + # Use pytest.assertion.util._reprcompare if that's available. + expl_call = self.helper( + "_call_reprcompare", + ast.Tuple(syms, ast.Load()), + ast.Tuple(load_names, ast.Load()), + ast.Tuple(expls, ast.Load()), + ast.Tuple(results, ast.Load()), + ) + if len(comp.ops) > 1: + res: ast.expr = ast.BoolOp(ast.And(), load_names) + else: + res = load_names[0] + + return res, self.explanation_param(self.pop_format_context(expl_call)) + + +def try_makedirs(cache_dir: Path) -> bool: + """Attempt to create the given directory and sub-directories exist. + + Returns True if successful or if it already exists. + """ + try: + os.makedirs(cache_dir, exist_ok=True) + except (FileNotFoundError, NotADirectoryError, FileExistsError): + # One of the path components was not a directory: + # - we're in a zip file + # - it is a file + return False + except PermissionError: + return False + except OSError as e: + # as of now, EROFS doesn't have an equivalent OSError-subclass + if e.errno == errno.EROFS: + return False + raise + return True + + +def get_cache_dir(file_path: Path) -> Path: + """Return the cache directory to write .pyc files for the given .py file path.""" + if sys.version_info >= (3, 8) and sys.pycache_prefix: + # given: + # prefix = '/tmp/pycs' + # path = '/home/user/proj/test_app.py' + # we want: + # '/tmp/pycs/home/user/proj' + return Path(sys.pycache_prefix) / Path(*file_path.parts[1:-1]) + else: + # classic pycache directory + return file_path.parent / "__pycache__" diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/assertion/truncate.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/assertion/truncate.py new file mode 100644 index 0000000000000000000000000000000000000000..dfd6f65d281a887540f81121b6dc2a0422ff191f --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/assertion/truncate.py @@ -0,0 +1,115 @@ +"""Utilities for truncating assertion output. + +Current default behaviour is to truncate assertion explanations at +~8 terminal lines, unless running in "-vv" mode or running on CI. +""" +from typing import List +from typing import Optional + +from _pytest.assertion import util +from _pytest.nodes import Item + + +DEFAULT_MAX_LINES = 8 +DEFAULT_MAX_CHARS = 8 * 80 +USAGE_MSG = "use '-vv' to show" + + +def truncate_if_required( + explanation: List[str], item: Item, max_length: Optional[int] = None +) -> List[str]: + """Truncate this assertion explanation if the given test item is eligible.""" + if _should_truncate_item(item): + return _truncate_explanation(explanation) + return explanation + + +def _should_truncate_item(item: Item) -> bool: + """Whether or not this test item is eligible for truncation.""" + verbose = item.config.option.verbose + return verbose < 2 and not util.running_on_ci() + + +def _truncate_explanation( + input_lines: List[str], + max_lines: Optional[int] = None, + max_chars: Optional[int] = None, +) -> List[str]: + """Truncate given list of strings that makes up the assertion explanation. + + Truncates to either 8 lines, or 640 characters - whichever the input reaches + first, taking the truncation explanation into account. The remaining lines + will be replaced by a usage message. + """ + if max_lines is None: + max_lines = DEFAULT_MAX_LINES + if max_chars is None: + max_chars = DEFAULT_MAX_CHARS + + # Check if truncation required + input_char_count = len("".join(input_lines)) + # The length of the truncation explanation depends on the number of lines + # removed but is at least 68 characters: + # The real value is + # 64 (for the base message: + # '...\n...Full output truncated (1 line hidden), use '-vv' to show")' + # ) + # + 1 (for plural) + # + int(math.log10(len(input_lines) - max_lines)) (number of hidden line, at least 1) + # + 3 for the '...' added to the truncated line + # But if there's more than 100 lines it's very likely that we're going to + # truncate, so we don't need the exact value using log10. + tolerable_max_chars = ( + max_chars + 70 # 64 + 1 (for plural) + 2 (for '99') + 3 for '...' + ) + # The truncation explanation add two lines to the output + tolerable_max_lines = max_lines + 2 + if ( + len(input_lines) <= tolerable_max_lines + and input_char_count <= tolerable_max_chars + ): + return input_lines + # Truncate first to max_lines, and then truncate to max_chars if necessary + truncated_explanation = input_lines[:max_lines] + truncated_char = True + # We reevaluate the need to truncate chars following removal of some lines + if len("".join(truncated_explanation)) > tolerable_max_chars: + truncated_explanation = _truncate_by_char_count( + truncated_explanation, max_chars + ) + else: + truncated_char = False + + truncated_line_count = len(input_lines) - len(truncated_explanation) + if truncated_explanation[-1]: + # Add ellipsis and take into account part-truncated final line + truncated_explanation[-1] = truncated_explanation[-1] + "..." + if truncated_char: + # It's possible that we did not remove any char from this line + truncated_line_count += 1 + else: + # Add proper ellipsis when we were able to fit a full line exactly + truncated_explanation[-1] = "..." + return truncated_explanation + [ + "", + f"...Full output truncated ({truncated_line_count} line" + f"{'' if truncated_line_count == 1 else 's'} hidden), {USAGE_MSG}", + ] + + +def _truncate_by_char_count(input_lines: List[str], max_chars: int) -> List[str]: + # Find point at which input length exceeds total allowed length + iterated_char_count = 0 + for iterated_index, input_line in enumerate(input_lines): + if iterated_char_count + len(input_line) > max_chars: + break + iterated_char_count += len(input_line) + + # Create truncated explanation with modified final line + truncated_result = input_lines[:iterated_index] + final_line = input_lines[iterated_index] + if final_line: + final_line_truncate_point = max_chars - iterated_char_count + final_line = final_line[:final_line_truncate_point] + truncated_result.append(final_line) + return truncated_result diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/assertion/util.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/assertion/util.py new file mode 100644 index 0000000000000000000000000000000000000000..fc5dfdbd5ba60c9c88cfaaf93ade5805422da824 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/assertion/util.py @@ -0,0 +1,522 @@ +"""Utilities for assertion debugging.""" +import collections.abc +import os +import pprint +from typing import AbstractSet +from typing import Any +from typing import Callable +from typing import Iterable +from typing import List +from typing import Mapping +from typing import Optional +from typing import Sequence +from unicodedata import normalize + +import _pytest._code +from _pytest import outcomes +from _pytest._io.saferepr import _pformat_dispatch +from _pytest._io.saferepr import saferepr +from _pytest._io.saferepr import saferepr_unlimited +from _pytest.config import Config + +# The _reprcompare attribute on the util module is used by the new assertion +# interpretation code and assertion rewriter to detect this plugin was +# loaded and in turn call the hooks defined here as part of the +# DebugInterpreter. +_reprcompare: Optional[Callable[[str, object, object], Optional[str]]] = None + +# Works similarly as _reprcompare attribute. Is populated with the hook call +# when pytest_runtest_setup is called. +_assertion_pass: Optional[Callable[[int, str, str], None]] = None + +# Config object which is assigned during pytest_runtest_protocol. +_config: Optional[Config] = None + + +def format_explanation(explanation: str) -> str: + r"""Format an explanation. + + Normally all embedded newlines are escaped, however there are + three exceptions: \n{, \n} and \n~. The first two are intended + cover nested explanations, see function and attribute explanations + for examples (.visit_Call(), visit_Attribute()). The last one is + for when one explanation needs to span multiple lines, e.g. when + displaying diffs. + """ + lines = _split_explanation(explanation) + result = _format_lines(lines) + return "\n".join(result) + + +def _split_explanation(explanation: str) -> List[str]: + r"""Return a list of individual lines in the explanation. + + This will return a list of lines split on '\n{', '\n}' and '\n~'. + Any other newlines will be escaped and appear in the line as the + literal '\n' characters. + """ + raw_lines = (explanation or "").split("\n") + lines = [raw_lines[0]] + for values in raw_lines[1:]: + if values and values[0] in ["{", "}", "~", ">"]: + lines.append(values) + else: + lines[-1] += "\\n" + values + return lines + + +def _format_lines(lines: Sequence[str]) -> List[str]: + """Format the individual lines. + + This will replace the '{', '}' and '~' characters of our mini formatting + language with the proper 'where ...', 'and ...' and ' + ...' text, taking + care of indentation along the way. + + Return a list of formatted lines. + """ + result = list(lines[:1]) + stack = [0] + stackcnt = [0] + for line in lines[1:]: + if line.startswith("{"): + if stackcnt[-1]: + s = "and " + else: + s = "where " + stack.append(len(result)) + stackcnt[-1] += 1 + stackcnt.append(0) + result.append(" +" + " " * (len(stack) - 1) + s + line[1:]) + elif line.startswith("}"): + stack.pop() + stackcnt.pop() + result[stack[-1]] += line[1:] + else: + assert line[0] in ["~", ">"] + stack[-1] += 1 + indent = len(stack) if line.startswith("~") else len(stack) - 1 + result.append(" " * indent + line[1:]) + assert len(stack) == 1 + return result + + +def issequence(x: Any) -> bool: + return isinstance(x, collections.abc.Sequence) and not isinstance(x, str) + + +def istext(x: Any) -> bool: + return isinstance(x, str) + + +def isdict(x: Any) -> bool: + return isinstance(x, dict) + + +def isset(x: Any) -> bool: + return isinstance(x, (set, frozenset)) + + +def isnamedtuple(obj: Any) -> bool: + return isinstance(obj, tuple) and getattr(obj, "_fields", None) is not None + + +def isdatacls(obj: Any) -> bool: + return getattr(obj, "__dataclass_fields__", None) is not None + + +def isattrs(obj: Any) -> bool: + return getattr(obj, "__attrs_attrs__", None) is not None + + +def isiterable(obj: Any) -> bool: + try: + iter(obj) + return not istext(obj) + except TypeError: + return False + + +def has_default_eq( + obj: object, +) -> bool: + """Check if an instance of an object contains the default eq + + First, we check if the object's __eq__ attribute has __code__, + if so, we check the equally of the method code filename (__code__.co_filename) + to the default one generated by the dataclass and attr module + for dataclasses the default co_filename is , for attrs class, the __eq__ should contain "attrs eq generated" + """ + # inspired from https://github.com/willmcgugan/rich/blob/07d51ffc1aee6f16bd2e5a25b4e82850fb9ed778/rich/pretty.py#L68 + if hasattr(obj.__eq__, "__code__") and hasattr(obj.__eq__.__code__, "co_filename"): + code_filename = obj.__eq__.__code__.co_filename + + if isattrs(obj): + return "attrs generated eq" in code_filename + + return code_filename == "" # data class + return True + + +def assertrepr_compare( + config, op: str, left: Any, right: Any, use_ascii: bool = False +) -> Optional[List[str]]: + """Return specialised explanations for some operators/operands.""" + verbose = config.getoption("verbose") + + # Strings which normalize equal are often hard to distinguish when printed; use ascii() to make this easier. + # See issue #3246. + use_ascii = ( + isinstance(left, str) + and isinstance(right, str) + and normalize("NFD", left) == normalize("NFD", right) + ) + + if verbose > 1: + left_repr = saferepr_unlimited(left, use_ascii=use_ascii) + right_repr = saferepr_unlimited(right, use_ascii=use_ascii) + else: + # XXX: "15 chars indentation" is wrong + # ("E AssertionError: assert "); should use term width. + maxsize = ( + 80 - 15 - len(op) - 2 + ) // 2 # 15 chars indentation, 1 space around op + + left_repr = saferepr(left, maxsize=maxsize, use_ascii=use_ascii) + right_repr = saferepr(right, maxsize=maxsize, use_ascii=use_ascii) + + summary = f"{left_repr} {op} {right_repr}" + + explanation = None + try: + if op == "==": + explanation = _compare_eq_any(left, right, verbose) + elif op == "not in": + if istext(left) and istext(right): + explanation = _notin_text(left, right, verbose) + except outcomes.Exit: + raise + except Exception: + explanation = [ + "(pytest_assertion plugin: representation of details failed: {}.".format( + _pytest._code.ExceptionInfo.from_current()._getreprcrash() + ), + " Probably an object has a faulty __repr__.)", + ] + + if not explanation: + return None + + return [summary] + explanation + + +def _compare_eq_any(left: Any, right: Any, verbose: int = 0) -> List[str]: + explanation = [] + if istext(left) and istext(right): + explanation = _diff_text(left, right, verbose) + else: + from _pytest.python_api import ApproxBase + + if isinstance(left, ApproxBase) or isinstance(right, ApproxBase): + # Although the common order should be obtained == expected, this ensures both ways + approx_side = left if isinstance(left, ApproxBase) else right + other_side = right if isinstance(left, ApproxBase) else left + + explanation = approx_side._repr_compare(other_side) + elif type(left) == type(right) and ( + isdatacls(left) or isattrs(left) or isnamedtuple(left) + ): + # Note: unlike dataclasses/attrs, namedtuples compare only the + # field values, not the type or field names. But this branch + # intentionally only handles the same-type case, which was often + # used in older code bases before dataclasses/attrs were available. + explanation = _compare_eq_cls(left, right, verbose) + elif issequence(left) and issequence(right): + explanation = _compare_eq_sequence(left, right, verbose) + elif isset(left) and isset(right): + explanation = _compare_eq_set(left, right, verbose) + elif isdict(left) and isdict(right): + explanation = _compare_eq_dict(left, right, verbose) + + if isiterable(left) and isiterable(right): + expl = _compare_eq_iterable(left, right, verbose) + explanation.extend(expl) + + return explanation + + +def _diff_text(left: str, right: str, verbose: int = 0) -> List[str]: + """Return the explanation for the diff between text. + + Unless --verbose is used this will skip leading and trailing + characters which are identical to keep the diff minimal. + """ + from difflib import ndiff + + explanation: List[str] = [] + + if verbose < 1: + i = 0 # just in case left or right has zero length + for i in range(min(len(left), len(right))): + if left[i] != right[i]: + break + if i > 42: + i -= 10 # Provide some context + explanation = [ + "Skipping %s identical leading characters in diff, use -v to show" % i + ] + left = left[i:] + right = right[i:] + if len(left) == len(right): + for i in range(len(left)): + if left[-i] != right[-i]: + break + if i > 42: + i -= 10 # Provide some context + explanation += [ + "Skipping {} identical trailing " + "characters in diff, use -v to show".format(i) + ] + left = left[:-i] + right = right[:-i] + keepends = True + if left.isspace() or right.isspace(): + left = repr(str(left)) + right = repr(str(right)) + explanation += ["Strings contain only whitespace, escaping them using repr()"] + # "right" is the expected base against which we compare "left", + # see https://github.com/pytest-dev/pytest/issues/3333 + explanation += [ + line.strip("\n") + for line in ndiff(right.splitlines(keepends), left.splitlines(keepends)) + ] + return explanation + + +def _surrounding_parens_on_own_lines(lines: List[str]) -> None: + """Move opening/closing parenthesis/bracket to own lines.""" + opening = lines[0][:1] + if opening in ["(", "[", "{"]: + lines[0] = " " + lines[0][1:] + lines[:] = [opening] + lines + closing = lines[-1][-1:] + if closing in [")", "]", "}"]: + lines[-1] = lines[-1][:-1] + "," + lines[:] = lines + [closing] + + +def _compare_eq_iterable( + left: Iterable[Any], right: Iterable[Any], verbose: int = 0 +) -> List[str]: + if verbose <= 0 and not running_on_ci(): + return ["Use -v to get more diff"] + # dynamic import to speedup pytest + import difflib + + left_formatting = pprint.pformat(left).splitlines() + right_formatting = pprint.pformat(right).splitlines() + + # Re-format for different output lengths. + lines_left = len(left_formatting) + lines_right = len(right_formatting) + if lines_left != lines_right: + left_formatting = _pformat_dispatch(left).splitlines() + right_formatting = _pformat_dispatch(right).splitlines() + + if lines_left > 1 or lines_right > 1: + _surrounding_parens_on_own_lines(left_formatting) + _surrounding_parens_on_own_lines(right_formatting) + + explanation = ["Full diff:"] + # "right" is the expected base against which we compare "left", + # see https://github.com/pytest-dev/pytest/issues/3333 + explanation.extend( + line.rstrip() for line in difflib.ndiff(right_formatting, left_formatting) + ) + return explanation + + +def _compare_eq_sequence( + left: Sequence[Any], right: Sequence[Any], verbose: int = 0 +) -> List[str]: + comparing_bytes = isinstance(left, bytes) and isinstance(right, bytes) + explanation: List[str] = [] + len_left = len(left) + len_right = len(right) + for i in range(min(len_left, len_right)): + if left[i] != right[i]: + if comparing_bytes: + # when comparing bytes, we want to see their ascii representation + # instead of their numeric values (#5260) + # using a slice gives us the ascii representation: + # >>> s = b'foo' + # >>> s[0] + # 102 + # >>> s[0:1] + # b'f' + left_value = left[i : i + 1] + right_value = right[i : i + 1] + else: + left_value = left[i] + right_value = right[i] + + explanation += [f"At index {i} diff: {left_value!r} != {right_value!r}"] + break + + if comparing_bytes: + # when comparing bytes, it doesn't help to show the "sides contain one or more + # items" longer explanation, so skip it + + return explanation + + len_diff = len_left - len_right + if len_diff: + if len_diff > 0: + dir_with_more = "Left" + extra = saferepr(left[len_right]) + else: + len_diff = 0 - len_diff + dir_with_more = "Right" + extra = saferepr(right[len_left]) + + if len_diff == 1: + explanation += [f"{dir_with_more} contains one more item: {extra}"] + else: + explanation += [ + "%s contains %d more items, first extra item: %s" + % (dir_with_more, len_diff, extra) + ] + return explanation + + +def _compare_eq_set( + left: AbstractSet[Any], right: AbstractSet[Any], verbose: int = 0 +) -> List[str]: + explanation = [] + diff_left = left - right + diff_right = right - left + if diff_left: + explanation.append("Extra items in the left set:") + for item in diff_left: + explanation.append(saferepr(item)) + if diff_right: + explanation.append("Extra items in the right set:") + for item in diff_right: + explanation.append(saferepr(item)) + return explanation + + +def _compare_eq_dict( + left: Mapping[Any, Any], right: Mapping[Any, Any], verbose: int = 0 +) -> List[str]: + explanation: List[str] = [] + set_left = set(left) + set_right = set(right) + common = set_left.intersection(set_right) + same = {k: left[k] for k in common if left[k] == right[k]} + if same and verbose < 2: + explanation += ["Omitting %s identical items, use -vv to show" % len(same)] + elif same: + explanation += ["Common items:"] + explanation += pprint.pformat(same).splitlines() + diff = {k for k in common if left[k] != right[k]} + if diff: + explanation += ["Differing items:"] + for k in diff: + explanation += [saferepr({k: left[k]}) + " != " + saferepr({k: right[k]})] + extra_left = set_left - set_right + len_extra_left = len(extra_left) + if len_extra_left: + explanation.append( + "Left contains %d more item%s:" + % (len_extra_left, "" if len_extra_left == 1 else "s") + ) + explanation.extend( + pprint.pformat({k: left[k] for k in extra_left}).splitlines() + ) + extra_right = set_right - set_left + len_extra_right = len(extra_right) + if len_extra_right: + explanation.append( + "Right contains %d more item%s:" + % (len_extra_right, "" if len_extra_right == 1 else "s") + ) + explanation.extend( + pprint.pformat({k: right[k] for k in extra_right}).splitlines() + ) + return explanation + + +def _compare_eq_cls(left: Any, right: Any, verbose: int) -> List[str]: + if not has_default_eq(left): + return [] + if isdatacls(left): + import dataclasses + + all_fields = dataclasses.fields(left) + fields_to_check = [info.name for info in all_fields if info.compare] + elif isattrs(left): + all_fields = left.__attrs_attrs__ + fields_to_check = [field.name for field in all_fields if getattr(field, "eq")] + elif isnamedtuple(left): + fields_to_check = left._fields + else: + assert False + + indent = " " + same = [] + diff = [] + for field in fields_to_check: + if getattr(left, field) == getattr(right, field): + same.append(field) + else: + diff.append(field) + + explanation = [] + if same or diff: + explanation += [""] + if same and verbose < 2: + explanation.append("Omitting %s identical items, use -vv to show" % len(same)) + elif same: + explanation += ["Matching attributes:"] + explanation += pprint.pformat(same).splitlines() + if diff: + explanation += ["Differing attributes:"] + explanation += pprint.pformat(diff).splitlines() + for field in diff: + field_left = getattr(left, field) + field_right = getattr(right, field) + explanation += [ + "", + "Drill down into differing attribute %s:" % field, + ("%s%s: %r != %r") % (indent, field, field_left, field_right), + ] + explanation += [ + indent + line + for line in _compare_eq_any(field_left, field_right, verbose) + ] + return explanation + + +def _notin_text(term: str, text: str, verbose: int = 0) -> List[str]: + index = text.find(term) + head = text[:index] + tail = text[index + len(term) :] + correct_text = head + tail + diff = _diff_text(text, correct_text, verbose) + newdiff = ["%s is contained here:" % saferepr(term, maxsize=42)] + for line in diff: + if line.startswith("Skipping"): + continue + if line.startswith("- "): + continue + if line.startswith("+ "): + newdiff.append(" " + line[2:]) + else: + newdiff.append(line) + return newdiff + + +def running_on_ci() -> bool: + """Check if we're currently running on a CI system.""" + env_vars = ["CI", "BUILD_NUMBER"] + return any(var in os.environ for var in env_vars) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e3990d175dfc067ec55e5adcab21c150c249fe8c --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/__init__.py @@ -0,0 +1,1816 @@ +"""Command line options, ini-file and conftest.py processing.""" +import argparse +import collections.abc +import copy +import dataclasses +import enum +import glob +import inspect +import os +import re +import shlex +import sys +import types +import warnings +from functools import lru_cache +from pathlib import Path +from textwrap import dedent +from types import FunctionType +from types import TracebackType +from typing import Any +from typing import Callable +from typing import cast +from typing import Dict +from typing import Generator +from typing import IO +from typing import Iterable +from typing import Iterator +from typing import List +from typing import Optional +from typing import Sequence +from typing import Set +from typing import TextIO +from typing import Tuple +from typing import Type +from typing import TYPE_CHECKING +from typing import Union + +from pluggy import HookimplMarker +from pluggy import HookspecMarker +from pluggy import PluginManager + +import _pytest._code +import _pytest.deprecated +import _pytest.hookspec +from .exceptions import PrintHelp as PrintHelp +from .exceptions import UsageError as UsageError +from .findpaths import determine_setup +from _pytest._code import ExceptionInfo +from _pytest._code import filter_traceback +from _pytest._io import TerminalWriter +from _pytest.compat import final +from _pytest.compat import importlib_metadata # type: ignore[attr-defined] +from _pytest.outcomes import fail +from _pytest.outcomes import Skipped +from _pytest.pathlib import absolutepath +from _pytest.pathlib import bestrelpath +from _pytest.pathlib import import_path +from _pytest.pathlib import ImportMode +from _pytest.pathlib import resolve_package_path +from _pytest.pathlib import safe_exists +from _pytest.stash import Stash +from _pytest.warning_types import PytestConfigWarning +from _pytest.warning_types import warn_explicit_for + +if TYPE_CHECKING: + from _pytest._code.code import _TracebackStyle + from _pytest.terminal import TerminalReporter + from .argparsing import Argument + + +_PluggyPlugin = object +"""A type to represent plugin objects. + +Plugins can be any namespace, so we can't narrow it down much, but we use an +alias to make the intent clear. + +Ideally this type would be provided by pluggy itself. +""" + + +hookimpl = HookimplMarker("pytest") +hookspec = HookspecMarker("pytest") + + +@final +class ExitCode(enum.IntEnum): + """Encodes the valid exit codes by pytest. + + Currently users and plugins may supply other exit codes as well. + + .. versionadded:: 5.0 + """ + + #: Tests passed. + OK = 0 + #: Tests failed. + TESTS_FAILED = 1 + #: pytest was interrupted. + INTERRUPTED = 2 + #: An internal error got in the way. + INTERNAL_ERROR = 3 + #: pytest was misused. + USAGE_ERROR = 4 + #: pytest couldn't find tests. + NO_TESTS_COLLECTED = 5 + + +class ConftestImportFailure(Exception): + def __init__( + self, + path: Path, + excinfo: Tuple[Type[Exception], Exception, TracebackType], + ) -> None: + super().__init__(path, excinfo) + self.path = path + self.excinfo = excinfo + + def __str__(self) -> str: + return "{}: {} (from {})".format( + self.excinfo[0].__name__, self.excinfo[1], self.path + ) + + +def filter_traceback_for_conftest_import_failure( + entry: _pytest._code.TracebackEntry, +) -> bool: + """Filter tracebacks entries which point to pytest internals or importlib. + + Make a special case for importlib because we use it to import test modules and conftest files + in _pytest.pathlib.import_path. + """ + return filter_traceback(entry) and "importlib" not in str(entry.path).split(os.sep) + + +def main( + args: Optional[Union[List[str], "os.PathLike[str]"]] = None, + plugins: Optional[Sequence[Union[str, _PluggyPlugin]]] = None, +) -> Union[int, ExitCode]: + """Perform an in-process test run. + + :param args: + List of command line arguments. If `None` or not given, defaults to reading + arguments directly from the process command line (:data:`sys.argv`). + :param plugins: List of plugin objects to be auto-registered during initialization. + + :returns: An exit code. + """ + try: + try: + config = _prepareconfig(args, plugins) + except ConftestImportFailure as e: + exc_info = ExceptionInfo.from_exc_info(e.excinfo) + tw = TerminalWriter(sys.stderr) + tw.line(f"ImportError while loading conftest '{e.path}'.", red=True) + exc_info.traceback = exc_info.traceback.filter( + filter_traceback_for_conftest_import_failure + ) + exc_repr = ( + exc_info.getrepr(style="short", chain=False) + if exc_info.traceback + else exc_info.exconly() + ) + formatted_tb = str(exc_repr) + for line in formatted_tb.splitlines(): + tw.line(line.rstrip(), red=True) + return ExitCode.USAGE_ERROR + else: + try: + ret: Union[ExitCode, int] = config.hook.pytest_cmdline_main( + config=config + ) + try: + return ExitCode(ret) + except ValueError: + return ret + finally: + config._ensure_unconfigure() + except UsageError as e: + tw = TerminalWriter(sys.stderr) + for msg in e.args: + tw.line(f"ERROR: {msg}\n", red=True) + return ExitCode.USAGE_ERROR + + +def console_main() -> int: + """The CLI entry point of pytest. + + This function is not meant for programmable use; use `main()` instead. + """ + # https://docs.python.org/3/library/signal.html#note-on-sigpipe + try: + code = main() + sys.stdout.flush() + return code + except BrokenPipeError: + # Python flushes standard streams on exit; redirect remaining output + # to devnull to avoid another BrokenPipeError at shutdown + devnull = os.open(os.devnull, os.O_WRONLY) + os.dup2(devnull, sys.stdout.fileno()) + return 1 # Python exits with error code 1 on EPIPE + + +class cmdline: # compatibility namespace + main = staticmethod(main) + + +def filename_arg(path: str, optname: str) -> str: + """Argparse type validator for filename arguments. + + :path: Path of filename. + :optname: Name of the option. + """ + if os.path.isdir(path): + raise UsageError(f"{optname} must be a filename, given: {path}") + return path + + +def directory_arg(path: str, optname: str) -> str: + """Argparse type validator for directory arguments. + + :path: Path of directory. + :optname: Name of the option. + """ + if not os.path.isdir(path): + raise UsageError(f"{optname} must be a directory, given: {path}") + return path + + +# Plugins that cannot be disabled via "-p no:X" currently. +essential_plugins = ( + "mark", + "main", + "runner", + "fixtures", + "helpconfig", # Provides -p. +) + +default_plugins = essential_plugins + ( + "python", + "terminal", + "debugging", + "unittest", + "capture", + "skipping", + "legacypath", + "tmpdir", + "monkeypatch", + "recwarn", + "pastebin", + "nose", + "assertion", + "junitxml", + "doctest", + "cacheprovider", + "freeze_support", + "setuponly", + "setupplan", + "stepwise", + "warnings", + "logging", + "reports", + "python_path", + *(["unraisableexception", "threadexception"] if sys.version_info >= (3, 8) else []), + "faulthandler", +) + +builtin_plugins = set(default_plugins) +builtin_plugins.add("pytester") +builtin_plugins.add("pytester_assertions") + + +def get_config( + args: Optional[List[str]] = None, + plugins: Optional[Sequence[Union[str, _PluggyPlugin]]] = None, +) -> "Config": + # subsequent calls to main will create a fresh instance + pluginmanager = PytestPluginManager() + config = Config( + pluginmanager, + invocation_params=Config.InvocationParams( + args=args or (), + plugins=plugins, + dir=Path.cwd(), + ), + ) + + if args is not None: + # Handle any "-p no:plugin" args. + pluginmanager.consider_preparse(args, exclude_only=True) + + for spec in default_plugins: + pluginmanager.import_plugin(spec) + + return config + + +def get_plugin_manager() -> "PytestPluginManager": + """Obtain a new instance of the + :py:class:`pytest.PytestPluginManager`, with default plugins + already loaded. + + This function can be used by integration with other tools, like hooking + into pytest to run tests into an IDE. + """ + return get_config().pluginmanager + + +def _prepareconfig( + args: Optional[Union[List[str], "os.PathLike[str]"]] = None, + plugins: Optional[Sequence[Union[str, _PluggyPlugin]]] = None, +) -> "Config": + if args is None: + args = sys.argv[1:] + elif isinstance(args, os.PathLike): + args = [os.fspath(args)] + elif not isinstance(args, list): + msg = ( # type:ignore[unreachable] + "`args` parameter expected to be a list of strings, got: {!r} (type: {})" + ) + raise TypeError(msg.format(args, type(args))) + + config = get_config(args, plugins) + pluginmanager = config.pluginmanager + try: + if plugins: + for plugin in plugins: + if isinstance(plugin, str): + pluginmanager.consider_pluginarg(plugin) + else: + pluginmanager.register(plugin) + config = pluginmanager.hook.pytest_cmdline_parse( + pluginmanager=pluginmanager, args=args + ) + return config + except BaseException: + config._ensure_unconfigure() + raise + + +def _get_directory(path: Path) -> Path: + """Get the directory of a path - itself if already a directory.""" + if path.is_file(): + return path.parent + else: + return path + + +def _get_legacy_hook_marks( + method: Any, + hook_type: str, + opt_names: Tuple[str, ...], +) -> Dict[str, bool]: + if TYPE_CHECKING: + # abuse typeguard from importlib to avoid massive method type union thats lacking a alias + assert inspect.isroutine(method) + known_marks: set[str] = {m.name for m in getattr(method, "pytestmark", [])} + must_warn: list[str] = [] + opts: dict[str, bool] = {} + for opt_name in opt_names: + opt_attr = getattr(method, opt_name, AttributeError) + if opt_attr is not AttributeError: + must_warn.append(f"{opt_name}={opt_attr}") + opts[opt_name] = True + elif opt_name in known_marks: + must_warn.append(f"{opt_name}=True") + opts[opt_name] = True + else: + opts[opt_name] = False + if must_warn: + hook_opts = ", ".join(must_warn) + message = _pytest.deprecated.HOOK_LEGACY_MARKING.format( + type=hook_type, + fullname=method.__qualname__, + hook_opts=hook_opts, + ) + warn_explicit_for(cast(FunctionType, method), message) + return opts + + +@final +class PytestPluginManager(PluginManager): + """A :py:class:`pluggy.PluginManager ` with + additional pytest-specific functionality: + + * Loading plugins from the command line, ``PYTEST_PLUGINS`` env variable and + ``pytest_plugins`` global variables found in plugins being loaded. + * ``conftest.py`` loading during start-up. + """ + + def __init__(self) -> None: + import _pytest.assertion + + super().__init__("pytest") + + # -- State related to local conftest plugins. + # All loaded conftest modules. + self._conftest_plugins: Set[types.ModuleType] = set() + # All conftest modules applicable for a directory. + # This includes the directory's own conftest modules as well + # as those of its parent directories. + self._dirpath2confmods: Dict[Path, List[types.ModuleType]] = {} + # Cutoff directory above which conftests are no longer discovered. + self._confcutdir: Optional[Path] = None + # If set, conftest loading is skipped. + self._noconftest = False + + # _getconftestmodules()'s call to _get_directory() causes a stat + # storm when it's called potentially thousands of times in a test + # session (#9478), often with the same path, so cache it. + self._get_directory = lru_cache(256)(_get_directory) + + self._duplicatepaths: Set[Path] = set() + + # plugins that were explicitly skipped with pytest.skip + # list of (module name, skip reason) + # previously we would issue a warning when a plugin was skipped, but + # since we refactored warnings as first citizens of Config, they are + # just stored here to be used later. + self.skipped_plugins: List[Tuple[str, str]] = [] + + self.add_hookspecs(_pytest.hookspec) + self.register(self) + if os.environ.get("PYTEST_DEBUG"): + err: IO[str] = sys.stderr + encoding: str = getattr(err, "encoding", "utf8") + try: + err = open( + os.dup(err.fileno()), + mode=err.mode, + buffering=1, + encoding=encoding, + ) + except Exception: + pass + self.trace.root.setwriter(err.write) + self.enable_tracing() + + # Config._consider_importhook will set a real object if required. + self.rewrite_hook = _pytest.assertion.DummyRewriteHook() + # Used to know when we are importing conftests after the pytest_configure stage. + self._configured = False + + def parse_hookimpl_opts(self, plugin: _PluggyPlugin, name: str): + # pytest hooks are always prefixed with "pytest_", + # so we avoid accessing possibly non-readable attributes + # (see issue #1073). + if not name.startswith("pytest_"): + return None + # Ignore names which can not be hooks. + if name == "pytest_plugins": + return None + + opts = super().parse_hookimpl_opts(plugin, name) + if opts is not None: + return opts + + method = getattr(plugin, name) + # Consider only actual functions for hooks (#3775). + if not inspect.isroutine(method): + return None + # Collect unmarked hooks as long as they have the `pytest_' prefix. + return _get_legacy_hook_marks( # type: ignore[return-value] + method, "impl", ("tryfirst", "trylast", "optionalhook", "hookwrapper") + ) + + def parse_hookspec_opts(self, module_or_class, name: str): + opts = super().parse_hookspec_opts(module_or_class, name) + if opts is None: + method = getattr(module_or_class, name) + if name.startswith("pytest_"): + opts = _get_legacy_hook_marks( # type: ignore[assignment] + method, + "spec", + ("firstresult", "historic"), + ) + return opts + + def register( + self, plugin: _PluggyPlugin, name: Optional[str] = None + ) -> Optional[str]: + if name in _pytest.deprecated.DEPRECATED_EXTERNAL_PLUGINS: + warnings.warn( + PytestConfigWarning( + "{} plugin has been merged into the core, " + "please remove it from your requirements.".format( + name.replace("_", "-") + ) + ) + ) + return None + ret: Optional[str] = super().register(plugin, name) + if ret: + self.hook.pytest_plugin_registered.call_historic( + kwargs=dict(plugin=plugin, manager=self) + ) + + if isinstance(plugin, types.ModuleType): + self.consider_module(plugin) + return ret + + def getplugin(self, name: str): + # Support deprecated naming because plugins (xdist e.g.) use it. + plugin: Optional[_PluggyPlugin] = self.get_plugin(name) + return plugin + + def hasplugin(self, name: str) -> bool: + """Return whether a plugin with the given name is registered.""" + return bool(self.get_plugin(name)) + + def pytest_configure(self, config: "Config") -> None: + """:meta private:""" + # XXX now that the pluginmanager exposes hookimpl(tryfirst...) + # we should remove tryfirst/trylast as markers. + config.addinivalue_line( + "markers", + "tryfirst: mark a hook implementation function such that the " + "plugin machinery will try to call it first/as early as possible. " + "DEPRECATED, use @pytest.hookimpl(tryfirst=True) instead.", + ) + config.addinivalue_line( + "markers", + "trylast: mark a hook implementation function such that the " + "plugin machinery will try to call it last/as late as possible. " + "DEPRECATED, use @pytest.hookimpl(trylast=True) instead.", + ) + self._configured = True + + # + # Internal API for local conftest plugin handling. + # + def _set_initial_conftests( + self, + args: Sequence[Union[str, Path]], + pyargs: bool, + noconftest: bool, + rootpath: Path, + confcutdir: Optional[Path], + importmode: Union[ImportMode, str], + ) -> None: + """Load initial conftest files given a preparsed "namespace". + + As conftest files may add their own command line options which have + arguments ('--my-opt somepath') we might get some false positives. + All builtin and 3rd party plugins will have been loaded, however, so + common options will not confuse our logic here. + """ + current = Path.cwd() + self._confcutdir = absolutepath(current / confcutdir) if confcutdir else None + self._noconftest = noconftest + self._using_pyargs = pyargs + foundanchor = False + for intitial_path in args: + path = str(intitial_path) + # remove node-id syntax + i = path.find("::") + if i != -1: + path = path[:i] + anchor = absolutepath(current / path) + + # Ensure we do not break if what appears to be an anchor + # is in fact a very long option (#10169, #11394). + if safe_exists(anchor): + self._try_load_conftest(anchor, importmode, rootpath) + foundanchor = True + if not foundanchor: + self._try_load_conftest(current, importmode, rootpath) + + def _is_in_confcutdir(self, path: Path) -> bool: + """Whether a path is within the confcutdir. + + When false, should not load conftest. + """ + if self._confcutdir is None: + return True + return path not in self._confcutdir.parents + + def _try_load_conftest( + self, anchor: Path, importmode: Union[str, ImportMode], rootpath: Path + ) -> None: + self._getconftestmodules(anchor, importmode, rootpath) + # let's also consider test* subdirs + if anchor.is_dir(): + for x in anchor.glob("test*"): + if x.is_dir(): + self._getconftestmodules(x, importmode, rootpath) + + def _getconftestmodules( + self, path: Path, importmode: Union[str, ImportMode], rootpath: Path + ) -> Sequence[types.ModuleType]: + if self._noconftest: + return [] + + directory = self._get_directory(path) + + # Optimization: avoid repeated searches in the same directory. + # Assumes always called with same importmode and rootpath. + existing_clist = self._dirpath2confmods.get(directory) + if existing_clist is not None: + return existing_clist + + # XXX these days we may rather want to use config.rootpath + # and allow users to opt into looking into the rootdir parent + # directories instead of requiring to specify confcutdir. + clist = [] + for parent in reversed((directory, *directory.parents)): + if self._is_in_confcutdir(parent): + conftestpath = parent / "conftest.py" + if conftestpath.is_file(): + mod = self._importconftest(conftestpath, importmode, rootpath) + clist.append(mod) + self._dirpath2confmods[directory] = clist + return clist + + def _rget_with_confmod( + self, + name: str, + path: Path, + importmode: Union[str, ImportMode], + rootpath: Path, + ) -> Tuple[types.ModuleType, Any]: + modules = self._getconftestmodules(path, importmode, rootpath=rootpath) + for mod in reversed(modules): + try: + return mod, getattr(mod, name) + except AttributeError: + continue + raise KeyError(name) + + def _importconftest( + self, conftestpath: Path, importmode: Union[str, ImportMode], rootpath: Path + ) -> types.ModuleType: + existing = self.get_plugin(str(conftestpath)) + if existing is not None: + return cast(types.ModuleType, existing) + + pkgpath = resolve_package_path(conftestpath) + if pkgpath is None: + _ensure_removed_sysmodule(conftestpath.stem) + + try: + mod = import_path(conftestpath, mode=importmode, root=rootpath) + except Exception as e: + assert e.__traceback__ is not None + exc_info = (type(e), e, e.__traceback__) + raise ConftestImportFailure(conftestpath, exc_info) from e + + self._check_non_top_pytest_plugins(mod, conftestpath) + + self._conftest_plugins.add(mod) + dirpath = conftestpath.parent + if dirpath in self._dirpath2confmods: + for path, mods in self._dirpath2confmods.items(): + if dirpath in path.parents or path == dirpath: + assert mod not in mods + mods.append(mod) + self.trace(f"loading conftestmodule {mod!r}") + self.consider_conftest(mod) + return mod + + def _check_non_top_pytest_plugins( + self, + mod: types.ModuleType, + conftestpath: Path, + ) -> None: + if ( + hasattr(mod, "pytest_plugins") + and self._configured + and not self._using_pyargs + ): + msg = ( + "Defining 'pytest_plugins' in a non-top-level conftest is no longer supported:\n" + "It affects the entire test suite instead of just below the conftest as expected.\n" + " {}\n" + "Please move it to a top level conftest file at the rootdir:\n" + " {}\n" + "For more information, visit:\n" + " https://docs.pytest.org/en/stable/deprecations.html#pytest-plugins-in-non-top-level-conftest-files" + ) + fail(msg.format(conftestpath, self._confcutdir), pytrace=False) + + # + # API for bootstrapping plugin loading + # + # + + def consider_preparse( + self, args: Sequence[str], *, exclude_only: bool = False + ) -> None: + """:meta private:""" + i = 0 + n = len(args) + while i < n: + opt = args[i] + i += 1 + if isinstance(opt, str): + if opt == "-p": + try: + parg = args[i] + except IndexError: + return + i += 1 + elif opt.startswith("-p"): + parg = opt[2:] + else: + continue + parg = parg.strip() + if exclude_only and not parg.startswith("no:"): + continue + self.consider_pluginarg(parg) + + def consider_pluginarg(self, arg: str) -> None: + """:meta private:""" + if arg.startswith("no:"): + name = arg[3:] + if name in essential_plugins: + raise UsageError("plugin %s cannot be disabled" % name) + + # PR #4304: remove stepwise if cacheprovider is blocked. + if name == "cacheprovider": + self.set_blocked("stepwise") + self.set_blocked("pytest_stepwise") + + self.set_blocked(name) + if not name.startswith("pytest_"): + self.set_blocked("pytest_" + name) + else: + name = arg + # Unblock the plugin. None indicates that it has been blocked. + # There is no interface with pluggy for this. + if self._name2plugin.get(name, -1) is None: + del self._name2plugin[name] + if not name.startswith("pytest_"): + if self._name2plugin.get("pytest_" + name, -1) is None: + del self._name2plugin["pytest_" + name] + self.import_plugin(arg, consider_entry_points=True) + + def consider_conftest(self, conftestmodule: types.ModuleType) -> None: + """:meta private:""" + self.register(conftestmodule, name=conftestmodule.__file__) + + def consider_env(self) -> None: + """:meta private:""" + self._import_plugin_specs(os.environ.get("PYTEST_PLUGINS")) + + def consider_module(self, mod: types.ModuleType) -> None: + """:meta private:""" + self._import_plugin_specs(getattr(mod, "pytest_plugins", [])) + + def _import_plugin_specs( + self, spec: Union[None, types.ModuleType, str, Sequence[str]] + ) -> None: + plugins = _get_plugin_specs_as_list(spec) + for import_spec in plugins: + self.import_plugin(import_spec) + + def import_plugin(self, modname: str, consider_entry_points: bool = False) -> None: + """Import a plugin with ``modname``. + + If ``consider_entry_points`` is True, entry point names are also + considered to find a plugin. + """ + # Most often modname refers to builtin modules, e.g. "pytester", + # "terminal" or "capture". Those plugins are registered under their + # basename for historic purposes but must be imported with the + # _pytest prefix. + assert isinstance(modname, str), ( + "module name as text required, got %r" % modname + ) + if self.is_blocked(modname) or self.get_plugin(modname) is not None: + return + + importspec = "_pytest." + modname if modname in builtin_plugins else modname + self.rewrite_hook.mark_rewrite(importspec) + + if consider_entry_points: + loaded = self.load_setuptools_entrypoints("pytest11", name=modname) + if loaded: + return + + try: + __import__(importspec) + except ImportError as e: + raise ImportError( + f'Error importing plugin "{modname}": {e.args[0]}' + ).with_traceback(e.__traceback__) from e + + except Skipped as e: + self.skipped_plugins.append((modname, e.msg or "")) + else: + mod = sys.modules[importspec] + self.register(mod, modname) + + +def _get_plugin_specs_as_list( + specs: Union[None, types.ModuleType, str, Sequence[str]] +) -> List[str]: + """Parse a plugins specification into a list of plugin names.""" + # None means empty. + if specs is None: + return [] + # Workaround for #3899 - a submodule which happens to be called "pytest_plugins". + if isinstance(specs, types.ModuleType): + return [] + # Comma-separated list. + if isinstance(specs, str): + return specs.split(",") if specs else [] + # Direct specification. + if isinstance(specs, collections.abc.Sequence): + return list(specs) + raise UsageError( + "Plugins may be specified as a sequence or a ','-separated string of plugin names. Got: %r" + % specs + ) + + +def _ensure_removed_sysmodule(modname: str) -> None: + try: + del sys.modules[modname] + except KeyError: + pass + + +class Notset: + def __repr__(self): + return "" + + +notset = Notset() + + +def _iter_rewritable_modules(package_files: Iterable[str]) -> Iterator[str]: + """Given an iterable of file names in a source distribution, return the "names" that should + be marked for assertion rewrite. + + For example the package "pytest_mock/__init__.py" should be added as "pytest_mock" in + the assertion rewrite mechanism. + + This function has to deal with dist-info based distributions and egg based distributions + (which are still very much in use for "editable" installs). + + Here are the file names as seen in a dist-info based distribution: + + pytest_mock/__init__.py + pytest_mock/_version.py + pytest_mock/plugin.py + pytest_mock.egg-info/PKG-INFO + + Here are the file names as seen in an egg based distribution: + + src/pytest_mock/__init__.py + src/pytest_mock/_version.py + src/pytest_mock/plugin.py + src/pytest_mock.egg-info/PKG-INFO + LICENSE + setup.py + + We have to take in account those two distribution flavors in order to determine which + names should be considered for assertion rewriting. + + More information: + https://github.com/pytest-dev/pytest-mock/issues/167 + """ + package_files = list(package_files) + seen_some = False + for fn in package_files: + is_simple_module = "/" not in fn and fn.endswith(".py") + is_package = fn.count("/") == 1 and fn.endswith("__init__.py") + if is_simple_module: + module_name, _ = os.path.splitext(fn) + # we ignore "setup.py" at the root of the distribution + # as well as editable installation finder modules made by setuptools + if module_name != "setup" and not module_name.startswith("__editable__"): + seen_some = True + yield module_name + elif is_package: + package_name = os.path.dirname(fn) + seen_some = True + yield package_name + + if not seen_some: + # At this point we did not find any packages or modules suitable for assertion + # rewriting, so we try again by stripping the first path component (to account for + # "src" based source trees for example). + # This approach lets us have the common case continue to be fast, as egg-distributions + # are rarer. + new_package_files = [] + for fn in package_files: + parts = fn.split("/") + new_fn = "/".join(parts[1:]) + if new_fn: + new_package_files.append(new_fn) + if new_package_files: + yield from _iter_rewritable_modules(new_package_files) + + +@final +class Config: + """Access to configuration values, pluginmanager and plugin hooks. + + :param PytestPluginManager pluginmanager: + A pytest PluginManager. + + :param InvocationParams invocation_params: + Object containing parameters regarding the :func:`pytest.main` + invocation. + """ + + @final + @dataclasses.dataclass(frozen=True) + class InvocationParams: + """Holds parameters passed during :func:`pytest.main`. + + The object attributes are read-only. + + .. versionadded:: 5.1 + + .. note:: + + Note that the environment variable ``PYTEST_ADDOPTS`` and the ``addopts`` + ini option are handled by pytest, not being included in the ``args`` attribute. + + Plugins accessing ``InvocationParams`` must be aware of that. + """ + + args: Tuple[str, ...] + """The command-line arguments as passed to :func:`pytest.main`.""" + plugins: Optional[Sequence[Union[str, _PluggyPlugin]]] + """Extra plugins, might be `None`.""" + dir: Path + """The directory from which :func:`pytest.main` was invoked.""" + + def __init__( + self, + *, + args: Iterable[str], + plugins: Optional[Sequence[Union[str, _PluggyPlugin]]], + dir: Path, + ) -> None: + object.__setattr__(self, "args", tuple(args)) + object.__setattr__(self, "plugins", plugins) + object.__setattr__(self, "dir", dir) + + class ArgsSource(enum.Enum): + """Indicates the source of the test arguments. + + .. versionadded:: 7.2 + """ + + #: Command line arguments. + ARGS = enum.auto() + #: Invocation directory. + INCOVATION_DIR = enum.auto() + #: 'testpaths' configuration value. + TESTPATHS = enum.auto() + + def __init__( + self, + pluginmanager: PytestPluginManager, + *, + invocation_params: Optional[InvocationParams] = None, + ) -> None: + from .argparsing import Parser, FILE_OR_DIR + + if invocation_params is None: + invocation_params = self.InvocationParams( + args=(), plugins=None, dir=Path.cwd() + ) + + self.option = argparse.Namespace() + """Access to command line option as attributes. + + :type: argparse.Namespace + """ + + self.invocation_params = invocation_params + """The parameters with which pytest was invoked. + + :type: InvocationParams + """ + + _a = FILE_OR_DIR + self._parser = Parser( + usage=f"%(prog)s [options] [{_a}] [{_a}] [...]", + processopt=self._processopt, + _ispytest=True, + ) + self.pluginmanager = pluginmanager + """The plugin manager handles plugin registration and hook invocation. + + :type: PytestPluginManager + """ + + self.stash = Stash() + """A place where plugins can store information on the config for their + own use. + + :type: Stash + """ + # Deprecated alias. Was never public. Can be removed in a few releases. + self._store = self.stash + + from .compat import PathAwareHookProxy + + self.trace = self.pluginmanager.trace.root.get("config") + self.hook = PathAwareHookProxy(self.pluginmanager.hook) + self._inicache: Dict[str, Any] = {} + self._override_ini: Sequence[str] = () + self._opt2dest: Dict[str, str] = {} + self._cleanup: List[Callable[[], None]] = [] + self.pluginmanager.register(self, "pytestconfig") + self._configured = False + self.hook.pytest_addoption.call_historic( + kwargs=dict(parser=self._parser, pluginmanager=self.pluginmanager) + ) + self.args_source = Config.ArgsSource.ARGS + self.args: List[str] = [] + + if TYPE_CHECKING: + from _pytest.cacheprovider import Cache + + self.cache: Optional[Cache] = None + + @property + def rootpath(self) -> Path: + """The path to the :ref:`rootdir `. + + :type: pathlib.Path + + .. versionadded:: 6.1 + """ + return self._rootpath + + @property + def inipath(self) -> Optional[Path]: + """The path to the :ref:`configfile `. + + :type: Optional[pathlib.Path] + + .. versionadded:: 6.1 + """ + return self._inipath + + def add_cleanup(self, func: Callable[[], None]) -> None: + """Add a function to be called when the config object gets out of + use (usually coinciding with pytest_unconfigure).""" + self._cleanup.append(func) + + def _do_configure(self) -> None: + assert not self._configured + self._configured = True + with warnings.catch_warnings(): + warnings.simplefilter("default") + self.hook.pytest_configure.call_historic(kwargs=dict(config=self)) + + def _ensure_unconfigure(self) -> None: + if self._configured: + self._configured = False + self.hook.pytest_unconfigure(config=self) + self.hook.pytest_configure._call_history = [] + while self._cleanup: + fin = self._cleanup.pop() + fin() + + def get_terminal_writer(self) -> TerminalWriter: + terminalreporter: Optional[TerminalReporter] = self.pluginmanager.get_plugin( + "terminalreporter" + ) + assert terminalreporter is not None + return terminalreporter._tw + + def pytest_cmdline_parse( + self, pluginmanager: PytestPluginManager, args: List[str] + ) -> "Config": + try: + self.parse(args) + except UsageError: + # Handle --version and --help here in a minimal fashion. + # This gets done via helpconfig normally, but its + # pytest_cmdline_main is not called in case of errors. + if getattr(self.option, "version", False) or "--version" in args: + from _pytest.helpconfig import showversion + + showversion(self) + elif ( + getattr(self.option, "help", False) or "--help" in args or "-h" in args + ): + self._parser._getparser().print_help() + sys.stdout.write( + "\nNOTE: displaying only minimal help due to UsageError.\n\n" + ) + + raise + + return self + + def notify_exception( + self, + excinfo: ExceptionInfo[BaseException], + option: Optional[argparse.Namespace] = None, + ) -> None: + if option and getattr(option, "fulltrace", False): + style: _TracebackStyle = "long" + else: + style = "native" + excrepr = excinfo.getrepr( + funcargs=True, showlocals=getattr(option, "showlocals", False), style=style + ) + res = self.hook.pytest_internalerror(excrepr=excrepr, excinfo=excinfo) + if not any(res): + for line in str(excrepr).split("\n"): + sys.stderr.write("INTERNALERROR> %s\n" % line) + sys.stderr.flush() + + def cwd_relative_nodeid(self, nodeid: str) -> str: + # nodeid's are relative to the rootpath, compute relative to cwd. + if self.invocation_params.dir != self.rootpath: + fullpath = self.rootpath / nodeid + nodeid = bestrelpath(self.invocation_params.dir, fullpath) + return nodeid + + @classmethod + def fromdictargs(cls, option_dict, args) -> "Config": + """Constructor usable for subprocesses.""" + config = get_config(args) + config.option.__dict__.update(option_dict) + config.parse(args, addopts=False) + for x in config.option.plugins: + config.pluginmanager.consider_pluginarg(x) + return config + + def _processopt(self, opt: "Argument") -> None: + for name in opt._short_opts + opt._long_opts: + self._opt2dest[name] = opt.dest + + if hasattr(opt, "default"): + if not hasattr(self.option, opt.dest): + setattr(self.option, opt.dest, opt.default) + + @hookimpl(trylast=True) + def pytest_load_initial_conftests(self, early_config: "Config") -> None: + # We haven't fully parsed the command line arguments yet, so + # early_config.args it not set yet. But we need it for + # discovering the initial conftests. So "pre-run" the logic here. + # It will be done for real in `parse()`. + args, args_source = early_config._decide_args( + args=early_config.known_args_namespace.file_or_dir, + pyargs=early_config.known_args_namespace.pyargs, + testpaths=early_config.getini("testpaths"), + invocation_dir=early_config.invocation_params.dir, + rootpath=early_config.rootpath, + warn=False, + ) + self.pluginmanager._set_initial_conftests( + args=args, + pyargs=early_config.known_args_namespace.pyargs, + noconftest=early_config.known_args_namespace.noconftest, + rootpath=early_config.rootpath, + confcutdir=early_config.known_args_namespace.confcutdir, + importmode=early_config.known_args_namespace.importmode, + ) + + def _initini(self, args: Sequence[str]) -> None: + ns, unknown_args = self._parser.parse_known_and_unknown_args( + args, namespace=copy.copy(self.option) + ) + rootpath, inipath, inicfg = determine_setup( + ns.inifilename, + ns.file_or_dir + unknown_args, + rootdir_cmd_arg=ns.rootdir or None, + config=self, + ) + self._rootpath = rootpath + self._inipath = inipath + self.inicfg = inicfg + self._parser.extra_info["rootdir"] = str(self.rootpath) + self._parser.extra_info["inifile"] = str(self.inipath) + self._parser.addini("addopts", "Extra command line options", "args") + self._parser.addini("minversion", "Minimally required pytest version") + self._parser.addini( + "required_plugins", + "Plugins that must be present for pytest to run", + type="args", + default=[], + ) + self._override_ini = ns.override_ini or () + + def _consider_importhook(self, args: Sequence[str]) -> None: + """Install the PEP 302 import hook if using assertion rewriting. + + Needs to parse the --assert= option from the commandline + and find all the installed plugins to mark them for rewriting + by the importhook. + """ + ns, unknown_args = self._parser.parse_known_and_unknown_args(args) + mode = getattr(ns, "assertmode", "plain") + if mode == "rewrite": + import _pytest.assertion + + try: + hook = _pytest.assertion.install_importhook(self) + except SystemError: + mode = "plain" + else: + self._mark_plugins_for_rewrite(hook) + self._warn_about_missing_assertion(mode) + + def _mark_plugins_for_rewrite(self, hook) -> None: + """Given an importhook, mark for rewrite any top-level + modules or packages in the distribution package for + all pytest plugins.""" + self.pluginmanager.rewrite_hook = hook + + if os.environ.get("PYTEST_DISABLE_PLUGIN_AUTOLOAD"): + # We don't autoload from setuptools entry points, no need to continue. + return + + package_files = ( + str(file) + for dist in importlib_metadata.distributions() + if any(ep.group == "pytest11" for ep in dist.entry_points) + for file in dist.files or [] + ) + + for name in _iter_rewritable_modules(package_files): + hook.mark_rewrite(name) + + def _validate_args(self, args: List[str], via: str) -> List[str]: + """Validate known args.""" + self._parser._config_source_hint = via # type: ignore + try: + self._parser.parse_known_and_unknown_args( + args, namespace=copy.copy(self.option) + ) + finally: + del self._parser._config_source_hint # type: ignore + + return args + + def _decide_args( + self, + *, + args: List[str], + pyargs: List[str], + testpaths: List[str], + invocation_dir: Path, + rootpath: Path, + warn: bool, + ) -> Tuple[List[str], ArgsSource]: + """Decide the args (initial paths/nodeids) to use given the relevant inputs. + + :param warn: Whether can issue warnings. + """ + if args: + source = Config.ArgsSource.ARGS + result = args + else: + if invocation_dir == rootpath: + source = Config.ArgsSource.TESTPATHS + if pyargs: + result = testpaths + else: + result = [] + for path in testpaths: + result.extend(sorted(glob.iglob(path, recursive=True))) + if testpaths and not result: + if warn: + warning_text = ( + "No files were found in testpaths; " + "consider removing or adjusting your testpaths configuration. " + "Searching recursively from the current directory instead." + ) + self.issue_config_time_warning( + PytestConfigWarning(warning_text), stacklevel=3 + ) + else: + result = [] + if not result: + source = Config.ArgsSource.INCOVATION_DIR + result = [str(invocation_dir)] + return result, source + + def _preparse(self, args: List[str], addopts: bool = True) -> None: + if addopts: + env_addopts = os.environ.get("PYTEST_ADDOPTS", "") + if len(env_addopts): + args[:] = ( + self._validate_args(shlex.split(env_addopts), "via PYTEST_ADDOPTS") + + args + ) + self._initini(args) + if addopts: + args[:] = ( + self._validate_args(self.getini("addopts"), "via addopts config") + args + ) + + self.known_args_namespace = self._parser.parse_known_args( + args, namespace=copy.copy(self.option) + ) + self._checkversion() + self._consider_importhook(args) + self.pluginmanager.consider_preparse(args, exclude_only=False) + if not os.environ.get("PYTEST_DISABLE_PLUGIN_AUTOLOAD"): + # Don't autoload from setuptools entry point. Only explicitly specified + # plugins are going to be loaded. + self.pluginmanager.load_setuptools_entrypoints("pytest11") + self.pluginmanager.consider_env() + + self.known_args_namespace = self._parser.parse_known_args( + args, namespace=copy.copy(self.known_args_namespace) + ) + + self._validate_plugins() + self._warn_about_skipped_plugins() + + if self.known_args_namespace.strict: + self.issue_config_time_warning( + _pytest.deprecated.STRICT_OPTION, stacklevel=2 + ) + + if self.known_args_namespace.confcutdir is None: + if self.inipath is not None: + confcutdir = str(self.inipath.parent) + else: + confcutdir = str(self.rootpath) + self.known_args_namespace.confcutdir = confcutdir + try: + self.hook.pytest_load_initial_conftests( + early_config=self, args=args, parser=self._parser + ) + except ConftestImportFailure as e: + if self.known_args_namespace.help or self.known_args_namespace.version: + # we don't want to prevent --help/--version to work + # so just let is pass and print a warning at the end + self.issue_config_time_warning( + PytestConfigWarning(f"could not load initial conftests: {e.path}"), + stacklevel=2, + ) + else: + raise + + @hookimpl(hookwrapper=True) + def pytest_collection(self) -> Generator[None, None, None]: + # Validate invalid ini keys after collection is done so we take in account + # options added by late-loading conftest files. + yield + self._validate_config_options() + + def _checkversion(self) -> None: + import pytest + + minver = self.inicfg.get("minversion", None) + if minver: + # Imported lazily to improve start-up time. + from packaging.version import Version + + if not isinstance(minver, str): + raise pytest.UsageError( + "%s: 'minversion' must be a single value" % self.inipath + ) + + if Version(minver) > Version(pytest.__version__): + raise pytest.UsageError( + "%s: 'minversion' requires pytest-%s, actual pytest-%s'" + % ( + self.inipath, + minver, + pytest.__version__, + ) + ) + + def _validate_config_options(self) -> None: + for key in sorted(self._get_unknown_ini_keys()): + self._warn_or_fail_if_strict(f"Unknown config option: {key}\n") + + def _validate_plugins(self) -> None: + required_plugins = sorted(self.getini("required_plugins")) + if not required_plugins: + return + + # Imported lazily to improve start-up time. + from packaging.version import Version + from packaging.requirements import InvalidRequirement, Requirement + + plugin_info = self.pluginmanager.list_plugin_distinfo() + plugin_dist_info = {dist.project_name: dist.version for _, dist in plugin_info} + + missing_plugins = [] + for required_plugin in required_plugins: + try: + req = Requirement(required_plugin) + except InvalidRequirement: + missing_plugins.append(required_plugin) + continue + + if req.name not in plugin_dist_info: + missing_plugins.append(required_plugin) + elif not req.specifier.contains( + Version(plugin_dist_info[req.name]), prereleases=True + ): + missing_plugins.append(required_plugin) + + if missing_plugins: + raise UsageError( + "Missing required plugins: {}".format(", ".join(missing_plugins)), + ) + + def _warn_or_fail_if_strict(self, message: str) -> None: + if self.known_args_namespace.strict_config: + raise UsageError(message) + + self.issue_config_time_warning(PytestConfigWarning(message), stacklevel=3) + + def _get_unknown_ini_keys(self) -> List[str]: + parser_inicfg = self._parser._inidict + return [name for name in self.inicfg if name not in parser_inicfg] + + def parse(self, args: List[str], addopts: bool = True) -> None: + # Parse given cmdline arguments into this config object. + assert ( + self.args == [] + ), "can only parse cmdline args at most once per Config object" + self.hook.pytest_addhooks.call_historic( + kwargs=dict(pluginmanager=self.pluginmanager) + ) + self._preparse(args, addopts=addopts) + # XXX deprecated hook: + self.hook.pytest_cmdline_preparse(config=self, args=args) + self._parser.after_preparse = True # type: ignore + try: + args = self._parser.parse_setoption( + args, self.option, namespace=self.option + ) + self.args, self.args_source = self._decide_args( + args=args, + pyargs=self.known_args_namespace.pyargs, + testpaths=self.getini("testpaths"), + invocation_dir=self.invocation_params.dir, + rootpath=self.rootpath, + warn=True, + ) + except PrintHelp: + pass + + def issue_config_time_warning(self, warning: Warning, stacklevel: int) -> None: + """Issue and handle a warning during the "configure" stage. + + During ``pytest_configure`` we can't capture warnings using the ``catch_warnings_for_item`` + function because it is not possible to have hookwrappers around ``pytest_configure``. + + This function is mainly intended for plugins that need to issue warnings during + ``pytest_configure`` (or similar stages). + + :param warning: The warning instance. + :param stacklevel: stacklevel forwarded to warnings.warn. + """ + if self.pluginmanager.is_blocked("warnings"): + return + + cmdline_filters = self.known_args_namespace.pythonwarnings or [] + config_filters = self.getini("filterwarnings") + + with warnings.catch_warnings(record=True) as records: + warnings.simplefilter("always", type(warning)) + apply_warning_filters(config_filters, cmdline_filters) + warnings.warn(warning, stacklevel=stacklevel) + + if records: + frame = sys._getframe(stacklevel - 1) + location = frame.f_code.co_filename, frame.f_lineno, frame.f_code.co_name + self.hook.pytest_warning_recorded.call_historic( + kwargs=dict( + warning_message=records[0], + when="config", + nodeid="", + location=location, + ) + ) + + def addinivalue_line(self, name: str, line: str) -> None: + """Add a line to an ini-file option. The option must have been + declared but might not yet be set in which case the line becomes + the first line in its value.""" + x = self.getini(name) + assert isinstance(x, list) + x.append(line) # modifies the cached list inline + + def getini(self, name: str): + """Return configuration value from an :ref:`ini file `. + + If the specified name hasn't been registered through a prior + :func:`parser.addini ` call (usually from a + plugin), a ValueError is raised. + """ + try: + return self._inicache[name] + except KeyError: + self._inicache[name] = val = self._getini(name) + return val + + # Meant for easy monkeypatching by legacypath plugin. + # Can be inlined back (with no cover removed) once legacypath is gone. + def _getini_unknown_type(self, name: str, type: str, value: Union[str, List[str]]): + msg = f"unknown configuration type: {type}" + raise ValueError(msg, value) # pragma: no cover + + def _getini(self, name: str): + try: + description, type, default = self._parser._inidict[name] + except KeyError as e: + raise ValueError(f"unknown configuration value: {name!r}") from e + override_value = self._get_override_ini_value(name) + if override_value is None: + try: + value = self.inicfg[name] + except KeyError: + if default is not None: + return default + if type is None: + return "" + return [] + else: + value = override_value + # Coerce the values based on types. + # + # Note: some coercions are only required if we are reading from .ini files, because + # the file format doesn't contain type information, but when reading from toml we will + # get either str or list of str values (see _parse_ini_config_from_pyproject_toml). + # For example: + # + # ini: + # a_line_list = "tests acceptance" + # in this case, we need to split the string to obtain a list of strings. + # + # toml: + # a_line_list = ["tests", "acceptance"] + # in this case, we already have a list ready to use. + # + if type == "paths": + # TODO: This assert is probably not valid in all cases. + assert self.inipath is not None + dp = self.inipath.parent + input_values = shlex.split(value) if isinstance(value, str) else value + return [dp / x for x in input_values] + elif type == "args": + return shlex.split(value) if isinstance(value, str) else value + elif type == "linelist": + if isinstance(value, str): + return [t for t in map(lambda x: x.strip(), value.split("\n")) if t] + else: + return value + elif type == "bool": + return _strtobool(str(value).strip()) + elif type == "string": + return value + elif type is None: + return value + else: + return self._getini_unknown_type(name, type, value) + + def _getconftest_pathlist( + self, name: str, path: Path, rootpath: Path + ) -> Optional[List[Path]]: + try: + mod, relroots = self.pluginmanager._rget_with_confmod( + name, path, self.getoption("importmode"), rootpath + ) + except KeyError: + return None + assert mod.__file__ is not None + modpath = Path(mod.__file__).parent + values: List[Path] = [] + for relroot in relroots: + if isinstance(relroot, os.PathLike): + relroot = Path(relroot) + else: + relroot = relroot.replace("/", os.sep) + relroot = absolutepath(modpath / relroot) + values.append(relroot) + return values + + def _get_override_ini_value(self, name: str) -> Optional[str]: + value = None + # override_ini is a list of "ini=value" options. + # Always use the last item if multiple values are set for same ini-name, + # e.g. -o foo=bar1 -o foo=bar2 will set foo to bar2. + for ini_config in self._override_ini: + try: + key, user_ini_value = ini_config.split("=", 1) + except ValueError as e: + raise UsageError( + "-o/--override-ini expects option=value style (got: {!r}).".format( + ini_config + ) + ) from e + else: + if key == name: + value = user_ini_value + return value + + def getoption(self, name: str, default=notset, skip: bool = False): + """Return command line option value. + + :param name: Name of the option. You may also specify + the literal ``--OPT`` option instead of the "dest" option name. + :param default: Default value if no option of that name exists. + :param skip: If True, raise pytest.skip if option does not exists + or has a None value. + """ + name = self._opt2dest.get(name, name) + try: + val = getattr(self.option, name) + if val is None and skip: + raise AttributeError(name) + return val + except AttributeError as e: + if default is not notset: + return default + if skip: + import pytest + + pytest.skip(f"no {name!r} option found") + raise ValueError(f"no option named {name!r}") from e + + def getvalue(self, name: str, path=None): + """Deprecated, use getoption() instead.""" + return self.getoption(name) + + def getvalueorskip(self, name: str, path=None): + """Deprecated, use getoption(skip=True) instead.""" + return self.getoption(name, skip=True) + + def _warn_about_missing_assertion(self, mode: str) -> None: + if not _assertion_supported(): + if mode == "plain": + warning_text = ( + "ASSERTIONS ARE NOT EXECUTED" + " and FAILING TESTS WILL PASS. Are you" + " using python -O?" + ) + else: + warning_text = ( + "assertions not in test modules or" + " plugins will be ignored" + " because assert statements are not executed " + "by the underlying Python interpreter " + "(are you using python -O?)\n" + ) + self.issue_config_time_warning( + PytestConfigWarning(warning_text), + stacklevel=3, + ) + + def _warn_about_skipped_plugins(self) -> None: + for module_name, msg in self.pluginmanager.skipped_plugins: + self.issue_config_time_warning( + PytestConfigWarning(f"skipped plugin {module_name!r}: {msg}"), + stacklevel=2, + ) + + +def _assertion_supported() -> bool: + try: + assert False + except AssertionError: + return True + else: + return False # type: ignore[unreachable] + + +def create_terminal_writer( + config: Config, file: Optional[TextIO] = None +) -> TerminalWriter: + """Create a TerminalWriter instance configured according to the options + in the config object. + + Every code which requires a TerminalWriter object and has access to a + config object should use this function. + """ + tw = TerminalWriter(file=file) + + if config.option.color == "yes": + tw.hasmarkup = True + elif config.option.color == "no": + tw.hasmarkup = False + + if config.option.code_highlight == "yes": + tw.code_highlight = True + elif config.option.code_highlight == "no": + tw.code_highlight = False + + return tw + + +def _strtobool(val: str) -> bool: + """Convert a string representation of truth to True or False. + + True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values + are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if + 'val' is anything else. + + .. note:: Copied from distutils.util. + """ + val = val.lower() + if val in ("y", "yes", "t", "true", "on", "1"): + return True + elif val in ("n", "no", "f", "false", "off", "0"): + return False + else: + raise ValueError(f"invalid truth value {val!r}") + + +@lru_cache(maxsize=50) +def parse_warning_filter( + arg: str, *, escape: bool +) -> Tuple["warnings._ActionKind", str, Type[Warning], str, int]: + """Parse a warnings filter string. + + This is copied from warnings._setoption with the following changes: + + * Does not apply the filter. + * Escaping is optional. + * Raises UsageError so we get nice error messages on failure. + """ + __tracebackhide__ = True + error_template = dedent( + f"""\ + while parsing the following warning configuration: + + {arg} + + This error occurred: + + {{error}} + """ + ) + + parts = arg.split(":") + if len(parts) > 5: + doc_url = ( + "https://docs.python.org/3/library/warnings.html#describing-warning-filters" + ) + error = dedent( + f"""\ + Too many fields ({len(parts)}), expected at most 5 separated by colons: + + action:message:category:module:line + + For more information please consult: {doc_url} + """ + ) + raise UsageError(error_template.format(error=error)) + + while len(parts) < 5: + parts.append("") + action_, message, category_, module, lineno_ = (s.strip() for s in parts) + try: + action: "warnings._ActionKind" = warnings._getaction(action_) # type: ignore[attr-defined] + except warnings._OptionError as e: + raise UsageError(error_template.format(error=str(e))) + try: + category: Type[Warning] = _resolve_warning_category(category_) + except Exception: + exc_info = ExceptionInfo.from_current() + exception_text = exc_info.getrepr(style="native") + raise UsageError(error_template.format(error=exception_text)) + if message and escape: + message = re.escape(message) + if module and escape: + module = re.escape(module) + r"\Z" + if lineno_: + try: + lineno = int(lineno_) + if lineno < 0: + raise ValueError("number is negative") + except ValueError as e: + raise UsageError( + error_template.format(error=f"invalid lineno {lineno_!r}: {e}") + ) + else: + lineno = 0 + return action, message, category, module, lineno + + +def _resolve_warning_category(category: str) -> Type[Warning]: + """ + Copied from warnings._getcategory, but changed so it lets exceptions (specially ImportErrors) + propagate so we can get access to their tracebacks (#9218). + """ + __tracebackhide__ = True + if not category: + return Warning + + if "." not in category: + import builtins as m + + klass = category + else: + module, _, klass = category.rpartition(".") + m = __import__(module, None, None, [klass]) + cat = getattr(m, klass) + if not issubclass(cat, Warning): + raise UsageError(f"{cat} is not a Warning subclass") + return cast(Type[Warning], cat) + + +def apply_warning_filters( + config_filters: Iterable[str], cmdline_filters: Iterable[str] +) -> None: + """Applies pytest-configured filters to the warnings module""" + # Filters should have this precedence: cmdline options, config. + # Filters should be applied in the inverse order of precedence. + for arg in config_filters: + warnings.filterwarnings(*parse_warning_filter(arg, escape=False)) + + for arg in cmdline_filters: + warnings.filterwarnings(*parse_warning_filter(arg, escape=True)) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..588d90dcec27d7c9185a46b4ae367d395cb51a7d Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/__pycache__/argparsing.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/__pycache__/argparsing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f13b400de44b8ced51ff76119573cadde1a4d2a9 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/__pycache__/argparsing.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/__pycache__/compat.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/__pycache__/compat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4759ff4b4b2e081d1e7767f601a1eda7a401e730 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/__pycache__/compat.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/__pycache__/exceptions.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ace25a98e2e32946d938d010ac1c1866a2a17a5 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/__pycache__/exceptions.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/__pycache__/findpaths.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/__pycache__/findpaths.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82d850c0f828c2b87697f33fca8ac0f56e2f7eac Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/__pycache__/findpaths.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/argparsing.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/argparsing.py new file mode 100644 index 0000000000000000000000000000000000000000..d3f01916b615d220069c9a2da97647a3a44aaf74 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/argparsing.py @@ -0,0 +1,551 @@ +import argparse +import os +import sys +import warnings +from gettext import gettext +from typing import Any +from typing import Callable +from typing import cast +from typing import Dict +from typing import List +from typing import Mapping +from typing import NoReturn +from typing import Optional +from typing import Sequence +from typing import Tuple +from typing import TYPE_CHECKING +from typing import Union + +import _pytest._io +from _pytest.compat import final +from _pytest.config.exceptions import UsageError +from _pytest.deprecated import ARGUMENT_PERCENT_DEFAULT +from _pytest.deprecated import ARGUMENT_TYPE_STR +from _pytest.deprecated import ARGUMENT_TYPE_STR_CHOICE +from _pytest.deprecated import check_ispytest + +if TYPE_CHECKING: + from typing_extensions import Literal + +FILE_OR_DIR = "file_or_dir" + + +@final +class Parser: + """Parser for command line arguments and ini-file values. + + :ivar extra_info: Dict of generic param -> value to display in case + there's an error processing the command line arguments. + """ + + prog: Optional[str] = None + + def __init__( + self, + usage: Optional[str] = None, + processopt: Optional[Callable[["Argument"], None]] = None, + *, + _ispytest: bool = False, + ) -> None: + check_ispytest(_ispytest) + self._anonymous = OptionGroup("Custom options", parser=self, _ispytest=True) + self._groups: List[OptionGroup] = [] + self._processopt = processopt + self._usage = usage + self._inidict: Dict[str, Tuple[str, Optional[str], Any]] = {} + self._ininames: List[str] = [] + self.extra_info: Dict[str, Any] = {} + + def processoption(self, option: "Argument") -> None: + if self._processopt: + if option.dest: + self._processopt(option) + + def getgroup( + self, name: str, description: str = "", after: Optional[str] = None + ) -> "OptionGroup": + """Get (or create) a named option Group. + + :param name: Name of the option group. + :param description: Long description for --help output. + :param after: Name of another group, used for ordering --help output. + :returns: The option group. + + The returned group object has an ``addoption`` method with the same + signature as :func:`parser.addoption ` but + will be shown in the respective group in the output of + ``pytest --help``. + """ + for group in self._groups: + if group.name == name: + return group + group = OptionGroup(name, description, parser=self, _ispytest=True) + i = 0 + for i, grp in enumerate(self._groups): + if grp.name == after: + break + self._groups.insert(i + 1, group) + return group + + def addoption(self, *opts: str, **attrs: Any) -> None: + """Register a command line option. + + :param opts: + Option names, can be short or long options. + :param attrs: + Same attributes as the argparse library's :py:func:`add_argument() + ` function accepts. + + After command line parsing, options are available on the pytest config + object via ``config.option.NAME`` where ``NAME`` is usually set + by passing a ``dest`` attribute, for example + ``addoption("--long", dest="NAME", ...)``. + """ + self._anonymous.addoption(*opts, **attrs) + + def parse( + self, + args: Sequence[Union[str, "os.PathLike[str]"]], + namespace: Optional[argparse.Namespace] = None, + ) -> argparse.Namespace: + from _pytest._argcomplete import try_argcomplete + + self.optparser = self._getparser() + try_argcomplete(self.optparser) + strargs = [os.fspath(x) for x in args] + return self.optparser.parse_args(strargs, namespace=namespace) + + def _getparser(self) -> "MyOptionParser": + from _pytest._argcomplete import filescompleter + + optparser = MyOptionParser(self, self.extra_info, prog=self.prog) + groups = self._groups + [self._anonymous] + for group in groups: + if group.options: + desc = group.description or group.name + arggroup = optparser.add_argument_group(desc) + for option in group.options: + n = option.names() + a = option.attrs() + arggroup.add_argument(*n, **a) + file_or_dir_arg = optparser.add_argument(FILE_OR_DIR, nargs="*") + # bash like autocompletion for dirs (appending '/') + # Type ignored because typeshed doesn't know about argcomplete. + file_or_dir_arg.completer = filescompleter # type: ignore + return optparser + + def parse_setoption( + self, + args: Sequence[Union[str, "os.PathLike[str]"]], + option: argparse.Namespace, + namespace: Optional[argparse.Namespace] = None, + ) -> List[str]: + parsedoption = self.parse(args, namespace=namespace) + for name, value in parsedoption.__dict__.items(): + setattr(option, name, value) + return cast(List[str], getattr(parsedoption, FILE_OR_DIR)) + + def parse_known_args( + self, + args: Sequence[Union[str, "os.PathLike[str]"]], + namespace: Optional[argparse.Namespace] = None, + ) -> argparse.Namespace: + """Parse the known arguments at this point. + + :returns: An argparse namespace object. + """ + return self.parse_known_and_unknown_args(args, namespace=namespace)[0] + + def parse_known_and_unknown_args( + self, + args: Sequence[Union[str, "os.PathLike[str]"]], + namespace: Optional[argparse.Namespace] = None, + ) -> Tuple[argparse.Namespace, List[str]]: + """Parse the known arguments at this point, and also return the + remaining unknown arguments. + + :returns: + A tuple containing an argparse namespace object for the known + arguments, and a list of the unknown arguments. + """ + optparser = self._getparser() + strargs = [os.fspath(x) for x in args] + return optparser.parse_known_args(strargs, namespace=namespace) + + def addini( + self, + name: str, + help: str, + type: Optional[ + "Literal['string', 'paths', 'pathlist', 'args', 'linelist', 'bool']" + ] = None, + default: Any = None, + ) -> None: + """Register an ini-file option. + + :param name: + Name of the ini-variable. + :param type: + Type of the variable. Can be: + + * ``string``: a string + * ``bool``: a boolean + * ``args``: a list of strings, separated as in a shell + * ``linelist``: a list of strings, separated by line breaks + * ``paths``: a list of :class:`pathlib.Path`, separated as in a shell + * ``pathlist``: a list of ``py.path``, separated as in a shell + + .. versionadded:: 7.0 + The ``paths`` variable type. + + Defaults to ``string`` if ``None`` or not passed. + :param default: + Default value if no ini-file option exists but is queried. + + The value of ini-variables can be retrieved via a call to + :py:func:`config.getini(name) `. + """ + assert type in (None, "string", "paths", "pathlist", "args", "linelist", "bool") + self._inidict[name] = (help, type, default) + self._ininames.append(name) + + +class ArgumentError(Exception): + """Raised if an Argument instance is created with invalid or + inconsistent arguments.""" + + def __init__(self, msg: str, option: Union["Argument", str]) -> None: + self.msg = msg + self.option_id = str(option) + + def __str__(self) -> str: + if self.option_id: + return f"option {self.option_id}: {self.msg}" + else: + return self.msg + + +class Argument: + """Class that mimics the necessary behaviour of optparse.Option. + + It's currently a least effort implementation and ignoring choices + and integer prefixes. + + https://docs.python.org/3/library/optparse.html#optparse-standard-option-types + """ + + _typ_map = {"int": int, "string": str, "float": float, "complex": complex} + + def __init__(self, *names: str, **attrs: Any) -> None: + """Store params in private vars for use in add_argument.""" + self._attrs = attrs + self._short_opts: List[str] = [] + self._long_opts: List[str] = [] + if "%default" in (attrs.get("help") or ""): + warnings.warn(ARGUMENT_PERCENT_DEFAULT, stacklevel=3) + try: + typ = attrs["type"] + except KeyError: + pass + else: + # This might raise a keyerror as well, don't want to catch that. + if isinstance(typ, str): + if typ == "choice": + warnings.warn( + ARGUMENT_TYPE_STR_CHOICE.format(typ=typ, names=names), + stacklevel=4, + ) + # argparse expects a type here take it from + # the type of the first element + attrs["type"] = type(attrs["choices"][0]) + else: + warnings.warn( + ARGUMENT_TYPE_STR.format(typ=typ, names=names), stacklevel=4 + ) + attrs["type"] = Argument._typ_map[typ] + # Used in test_parseopt -> test_parse_defaultgetter. + self.type = attrs["type"] + else: + self.type = typ + try: + # Attribute existence is tested in Config._processopt. + self.default = attrs["default"] + except KeyError: + pass + self._set_opt_strings(names) + dest: Optional[str] = attrs.get("dest") + if dest: + self.dest = dest + elif self._long_opts: + self.dest = self._long_opts[0][2:].replace("-", "_") + else: + try: + self.dest = self._short_opts[0][1:] + except IndexError as e: + self.dest = "???" # Needed for the error repr. + raise ArgumentError("need a long or short option", self) from e + + def names(self) -> List[str]: + return self._short_opts + self._long_opts + + def attrs(self) -> Mapping[str, Any]: + # Update any attributes set by processopt. + attrs = "default dest help".split() + attrs.append(self.dest) + for attr in attrs: + try: + self._attrs[attr] = getattr(self, attr) + except AttributeError: + pass + if self._attrs.get("help"): + a = self._attrs["help"] + a = a.replace("%default", "%(default)s") + # a = a.replace('%prog', '%(prog)s') + self._attrs["help"] = a + return self._attrs + + def _set_opt_strings(self, opts: Sequence[str]) -> None: + """Directly from optparse. + + Might not be necessary as this is passed to argparse later on. + """ + for opt in opts: + if len(opt) < 2: + raise ArgumentError( + "invalid option string %r: " + "must be at least two characters long" % opt, + self, + ) + elif len(opt) == 2: + if not (opt[0] == "-" and opt[1] != "-"): + raise ArgumentError( + "invalid short option string %r: " + "must be of the form -x, (x any non-dash char)" % opt, + self, + ) + self._short_opts.append(opt) + else: + if not (opt[0:2] == "--" and opt[2] != "-"): + raise ArgumentError( + "invalid long option string %r: " + "must start with --, followed by non-dash" % opt, + self, + ) + self._long_opts.append(opt) + + def __repr__(self) -> str: + args: List[str] = [] + if self._short_opts: + args += ["_short_opts: " + repr(self._short_opts)] + if self._long_opts: + args += ["_long_opts: " + repr(self._long_opts)] + args += ["dest: " + repr(self.dest)] + if hasattr(self, "type"): + args += ["type: " + repr(self.type)] + if hasattr(self, "default"): + args += ["default: " + repr(self.default)] + return "Argument({})".format(", ".join(args)) + + +class OptionGroup: + """A group of options shown in its own section.""" + + def __init__( + self, + name: str, + description: str = "", + parser: Optional[Parser] = None, + *, + _ispytest: bool = False, + ) -> None: + check_ispytest(_ispytest) + self.name = name + self.description = description + self.options: List[Argument] = [] + self.parser = parser + + def addoption(self, *opts: str, **attrs: Any) -> None: + """Add an option to this group. + + If a shortened version of a long option is specified, it will + be suppressed in the help. ``addoption('--twowords', '--two-words')`` + results in help showing ``--two-words`` only, but ``--twowords`` gets + accepted **and** the automatic destination is in ``args.twowords``. + + :param opts: + Option names, can be short or long options. + :param attrs: + Same attributes as the argparse library's :py:func:`add_argument() + ` function accepts. + """ + conflict = set(opts).intersection( + name for opt in self.options for name in opt.names() + ) + if conflict: + raise ValueError("option names %s already added" % conflict) + option = Argument(*opts, **attrs) + self._addoption_instance(option, shortupper=False) + + def _addoption(self, *opts: str, **attrs: Any) -> None: + option = Argument(*opts, **attrs) + self._addoption_instance(option, shortupper=True) + + def _addoption_instance(self, option: "Argument", shortupper: bool = False) -> None: + if not shortupper: + for opt in option._short_opts: + if opt[0] == "-" and opt[1].islower(): + raise ValueError("lowercase shortoptions reserved") + if self.parser: + self.parser.processoption(option) + self.options.append(option) + + +class MyOptionParser(argparse.ArgumentParser): + def __init__( + self, + parser: Parser, + extra_info: Optional[Dict[str, Any]] = None, + prog: Optional[str] = None, + ) -> None: + self._parser = parser + super().__init__( + prog=prog, + usage=parser._usage, + add_help=False, + formatter_class=DropShorterLongHelpFormatter, + allow_abbrev=False, + ) + # extra_info is a dict of (param -> value) to display if there's + # an usage error to provide more contextual information to the user. + self.extra_info = extra_info if extra_info else {} + + def error(self, message: str) -> NoReturn: + """Transform argparse error message into UsageError.""" + msg = f"{self.prog}: error: {message}" + + if hasattr(self._parser, "_config_source_hint"): + # Type ignored because the attribute is set dynamically. + msg = f"{msg} ({self._parser._config_source_hint})" # type: ignore + + raise UsageError(self.format_usage() + msg) + + # Type ignored because typeshed has a very complex type in the superclass. + def parse_args( # type: ignore + self, + args: Optional[Sequence[str]] = None, + namespace: Optional[argparse.Namespace] = None, + ) -> argparse.Namespace: + """Allow splitting of positional arguments.""" + parsed, unrecognized = self.parse_known_args(args, namespace) + if unrecognized: + for arg in unrecognized: + if arg and arg[0] == "-": + lines = ["unrecognized arguments: %s" % (" ".join(unrecognized))] + for k, v in sorted(self.extra_info.items()): + lines.append(f" {k}: {v}") + self.error("\n".join(lines)) + getattr(parsed, FILE_OR_DIR).extend(unrecognized) + return parsed + + if sys.version_info[:2] < (3, 9): # pragma: no cover + # Backport of https://github.com/python/cpython/pull/14316 so we can + # disable long --argument abbreviations without breaking short flags. + def _parse_optional( + self, arg_string: str + ) -> Optional[Tuple[Optional[argparse.Action], str, Optional[str]]]: + if not arg_string: + return None + if not arg_string[0] in self.prefix_chars: + return None + if arg_string in self._option_string_actions: + action = self._option_string_actions[arg_string] + return action, arg_string, None + if len(arg_string) == 1: + return None + if "=" in arg_string: + option_string, explicit_arg = arg_string.split("=", 1) + if option_string in self._option_string_actions: + action = self._option_string_actions[option_string] + return action, option_string, explicit_arg + if self.allow_abbrev or not arg_string.startswith("--"): + option_tuples = self._get_option_tuples(arg_string) + if len(option_tuples) > 1: + msg = gettext( + "ambiguous option: %(option)s could match %(matches)s" + ) + options = ", ".join(option for _, option, _ in option_tuples) + self.error(msg % {"option": arg_string, "matches": options}) + elif len(option_tuples) == 1: + (option_tuple,) = option_tuples + return option_tuple + if self._negative_number_matcher.match(arg_string): + if not self._has_negative_number_optionals: + return None + if " " in arg_string: + return None + return None, arg_string, None + + +class DropShorterLongHelpFormatter(argparse.HelpFormatter): + """Shorten help for long options that differ only in extra hyphens. + + - Collapse **long** options that are the same except for extra hyphens. + - Shortcut if there are only two options and one of them is a short one. + - Cache result on the action object as this is called at least 2 times. + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + # Use more accurate terminal width. + if "width" not in kwargs: + kwargs["width"] = _pytest._io.get_terminal_width() + super().__init__(*args, **kwargs) + + def _format_action_invocation(self, action: argparse.Action) -> str: + orgstr = super()._format_action_invocation(action) + if orgstr and orgstr[0] != "-": # only optional arguments + return orgstr + res: Optional[str] = getattr(action, "_formatted_action_invocation", None) + if res: + return res + options = orgstr.split(", ") + if len(options) == 2 and (len(options[0]) == 2 or len(options[1]) == 2): + # a shortcut for '-h, --help' or '--abc', '-a' + action._formatted_action_invocation = orgstr # type: ignore + return orgstr + return_list = [] + short_long: Dict[str, str] = {} + for option in options: + if len(option) == 2 or option[2] == " ": + continue + if not option.startswith("--"): + raise ArgumentError( + 'long optional argument without "--": [%s]' % (option), option + ) + xxoption = option[2:] + shortened = xxoption.replace("-", "") + if shortened not in short_long or len(short_long[shortened]) < len( + xxoption + ): + short_long[shortened] = xxoption + # now short_long has been filled out to the longest with dashes + # **and** we keep the right option ordering from add_argument + for option in options: + if len(option) == 2 or option[2] == " ": + return_list.append(option) + if option[2:] == short_long.get(option.replace("-", "")): + return_list.append(option.replace(" ", "=", 1)) + formatted_action_invocation = ", ".join(return_list) + action._formatted_action_invocation = formatted_action_invocation # type: ignore + return formatted_action_invocation + + def _split_lines(self, text, width): + """Wrap lines after splitting on original newlines. + + This allows to have explicit line breaks in the help text. + """ + import textwrap + + lines = [] + for line in text.splitlines(): + lines.extend(textwrap.wrap(line.strip(), width)) + return lines diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/compat.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd922a4a87a4423f367ba302df9a3a50ede5b45 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/compat.py @@ -0,0 +1,70 @@ +import functools +import warnings +from pathlib import Path +from typing import Optional + +from ..compat import LEGACY_PATH +from ..compat import legacy_path +from ..deprecated import HOOK_LEGACY_PATH_ARG +from _pytest.nodes import _check_path + +# hookname: (Path, LEGACY_PATH) +imply_paths_hooks = { + "pytest_ignore_collect": ("collection_path", "path"), + "pytest_collect_file": ("file_path", "path"), + "pytest_pycollect_makemodule": ("module_path", "path"), + "pytest_report_header": ("start_path", "startdir"), + "pytest_report_collectionfinish": ("start_path", "startdir"), +} + + +class PathAwareHookProxy: + """ + this helper wraps around hook callers + until pluggy supports fixingcalls, this one will do + + it currently doesn't return full hook caller proxies for fixed hooks, + this may have to be changed later depending on bugs + """ + + def __init__(self, hook_caller): + self.__hook_caller = hook_caller + + def __dir__(self): + return dir(self.__hook_caller) + + def __getattr__(self, key, _wraps=functools.wraps): + hook = getattr(self.__hook_caller, key) + if key not in imply_paths_hooks: + self.__dict__[key] = hook + return hook + else: + path_var, fspath_var = imply_paths_hooks[key] + + @_wraps(hook) + def fixed_hook(**kw): + path_value: Optional[Path] = kw.pop(path_var, None) + fspath_value: Optional[LEGACY_PATH] = kw.pop(fspath_var, None) + if fspath_value is not None: + warnings.warn( + HOOK_LEGACY_PATH_ARG.format( + pylib_path_arg=fspath_var, pathlib_path_arg=path_var + ), + stacklevel=2, + ) + if path_value is not None: + if fspath_value is not None: + _check_path(path_value, fspath_value) + else: + fspath_value = legacy_path(path_value) + else: + assert fspath_value is not None + path_value = Path(fspath_value) + + kw[path_var] = path_value + kw[fspath_var] = fspath_value + return hook(**kw) + + fixed_hook.__name__ = key + self.__dict__[key] = fixed_hook + return fixed_hook diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/exceptions.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..4f1320e758d506763261c4bd8dc21453dda4b5ef --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/exceptions.py @@ -0,0 +1,11 @@ +from _pytest.compat import final + + +@final +class UsageError(Exception): + """Error in pytest usage or invocation.""" + + +class PrintHelp(Exception): + """Raised when pytest should print its help to skip the rest of the + argument parsing and validation.""" diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/findpaths.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/findpaths.py new file mode 100644 index 0000000000000000000000000000000000000000..02674ffae3b757001bc3c688bb914c3425b810dd --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/config/findpaths.py @@ -0,0 +1,218 @@ +import os +import sys +from pathlib import Path +from typing import Dict +from typing import Iterable +from typing import List +from typing import Optional +from typing import Sequence +from typing import Tuple +from typing import TYPE_CHECKING +from typing import Union + +import iniconfig + +from .exceptions import UsageError +from _pytest.outcomes import fail +from _pytest.pathlib import absolutepath +from _pytest.pathlib import commonpath +from _pytest.pathlib import safe_exists + +if TYPE_CHECKING: + from . import Config + + +def _parse_ini_config(path: Path) -> iniconfig.IniConfig: + """Parse the given generic '.ini' file using legacy IniConfig parser, returning + the parsed object. + + Raise UsageError if the file cannot be parsed. + """ + try: + return iniconfig.IniConfig(str(path)) + except iniconfig.ParseError as exc: + raise UsageError(str(exc)) from exc + + +def load_config_dict_from_file( + filepath: Path, +) -> Optional[Dict[str, Union[str, List[str]]]]: + """Load pytest configuration from the given file path, if supported. + + Return None if the file does not contain valid pytest configuration. + """ + + # Configuration from ini files are obtained from the [pytest] section, if present. + if filepath.suffix == ".ini": + iniconfig = _parse_ini_config(filepath) + + if "pytest" in iniconfig: + return dict(iniconfig["pytest"].items()) + else: + # "pytest.ini" files are always the source of configuration, even if empty. + if filepath.name == "pytest.ini": + return {} + + # '.cfg' files are considered if they contain a "[tool:pytest]" section. + elif filepath.suffix == ".cfg": + iniconfig = _parse_ini_config(filepath) + + if "tool:pytest" in iniconfig.sections: + return dict(iniconfig["tool:pytest"].items()) + elif "pytest" in iniconfig.sections: + # If a setup.cfg contains a "[pytest]" section, we raise a failure to indicate users that + # plain "[pytest]" sections in setup.cfg files is no longer supported (#3086). + fail(CFG_PYTEST_SECTION.format(filename="setup.cfg"), pytrace=False) + + # '.toml' files are considered if they contain a [tool.pytest.ini_options] table. + elif filepath.suffix == ".toml": + if sys.version_info >= (3, 11): + import tomllib + else: + import tomli as tomllib + + toml_text = filepath.read_text(encoding="utf-8") + try: + config = tomllib.loads(toml_text) + except tomllib.TOMLDecodeError as exc: + raise UsageError(f"{filepath}: {exc}") from exc + + result = config.get("tool", {}).get("pytest", {}).get("ini_options", None) + if result is not None: + # TOML supports richer data types than ini files (strings, arrays, floats, ints, etc), + # however we need to convert all scalar values to str for compatibility with the rest + # of the configuration system, which expects strings only. + def make_scalar(v: object) -> Union[str, List[str]]: + return v if isinstance(v, list) else str(v) + + return {k: make_scalar(v) for k, v in result.items()} + + return None + + +def locate_config( + args: Iterable[Path], +) -> Tuple[Optional[Path], Optional[Path], Dict[str, Union[str, List[str]]]]: + """Search in the list of arguments for a valid ini-file for pytest, + and return a tuple of (rootdir, inifile, cfg-dict).""" + config_names = [ + "pytest.ini", + ".pytest.ini", + "pyproject.toml", + "tox.ini", + "setup.cfg", + ] + args = [x for x in args if not str(x).startswith("-")] + if not args: + args = [Path.cwd()] + for arg in args: + argpath = absolutepath(arg) + for base in (argpath, *argpath.parents): + for config_name in config_names: + p = base / config_name + if p.is_file(): + ini_config = load_config_dict_from_file(p) + if ini_config is not None: + return base, p, ini_config + return None, None, {} + + +def get_common_ancestor(paths: Iterable[Path]) -> Path: + common_ancestor: Optional[Path] = None + for path in paths: + if not path.exists(): + continue + if common_ancestor is None: + common_ancestor = path + else: + if common_ancestor in path.parents or path == common_ancestor: + continue + elif path in common_ancestor.parents: + common_ancestor = path + else: + shared = commonpath(path, common_ancestor) + if shared is not None: + common_ancestor = shared + if common_ancestor is None: + common_ancestor = Path.cwd() + elif common_ancestor.is_file(): + common_ancestor = common_ancestor.parent + return common_ancestor + + +def get_dirs_from_args(args: Iterable[str]) -> List[Path]: + def is_option(x: str) -> bool: + return x.startswith("-") + + def get_file_part_from_node_id(x: str) -> str: + return x.split("::")[0] + + def get_dir_from_path(path: Path) -> Path: + if path.is_dir(): + return path + return path.parent + + # These look like paths but may not exist + possible_paths = ( + absolutepath(get_file_part_from_node_id(arg)) + for arg in args + if not is_option(arg) + ) + + return [get_dir_from_path(path) for path in possible_paths if safe_exists(path)] + + +CFG_PYTEST_SECTION = "[pytest] section in {filename} files is no longer supported, change to [tool:pytest] instead." + + +def determine_setup( + inifile: Optional[str], + args: Sequence[str], + rootdir_cmd_arg: Optional[str] = None, + config: Optional["Config"] = None, +) -> Tuple[Path, Optional[Path], Dict[str, Union[str, List[str]]]]: + rootdir = None + dirs = get_dirs_from_args(args) + if inifile: + inipath_ = absolutepath(inifile) + inipath: Optional[Path] = inipath_ + inicfg = load_config_dict_from_file(inipath_) or {} + if rootdir_cmd_arg is None: + rootdir = inipath_.parent + else: + ancestor = get_common_ancestor(dirs) + rootdir, inipath, inicfg = locate_config([ancestor]) + if rootdir is None and rootdir_cmd_arg is None: + for possible_rootdir in (ancestor, *ancestor.parents): + if (possible_rootdir / "setup.py").is_file(): + rootdir = possible_rootdir + break + else: + if dirs != [ancestor]: + rootdir, inipath, inicfg = locate_config(dirs) + if rootdir is None: + if config is not None: + cwd = config.invocation_params.dir + else: + cwd = Path.cwd() + rootdir = get_common_ancestor([cwd, ancestor]) + if is_fs_root(rootdir): + rootdir = ancestor + if rootdir_cmd_arg: + rootdir = absolutepath(os.path.expandvars(rootdir_cmd_arg)) + if not rootdir.is_dir(): + raise UsageError( + "Directory '{}' not found. Check your '--rootdir' option.".format( + rootdir + ) + ) + assert rootdir is not None + return rootdir, inipath, inicfg or {} + + +def is_fs_root(p: Path) -> bool: + r""" + Return True if the given path is pointing to the root of the + file system ("/" on Unix and "C:\\" on Windows for example). + """ + return os.path.splitdrive(str(p))[1] == os.sep diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/mark/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/mark/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..de46b4c8a75e138843987a87d73bbd3b10755c2d --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/mark/__init__.py @@ -0,0 +1,269 @@ +"""Generic mechanism for marking and selecting python functions.""" +import dataclasses +from typing import AbstractSet +from typing import Collection +from typing import List +from typing import Optional +from typing import TYPE_CHECKING +from typing import Union + +from .expression import Expression +from .expression import ParseError +from .structures import EMPTY_PARAMETERSET_OPTION +from .structures import get_empty_parameterset_mark +from .structures import Mark +from .structures import MARK_GEN +from .structures import MarkDecorator +from .structures import MarkGenerator +from .structures import ParameterSet +from _pytest.config import Config +from _pytest.config import ExitCode +from _pytest.config import hookimpl +from _pytest.config import UsageError +from _pytest.config.argparsing import Parser +from _pytest.stash import StashKey + +if TYPE_CHECKING: + from _pytest.nodes import Item + + +__all__ = [ + "MARK_GEN", + "Mark", + "MarkDecorator", + "MarkGenerator", + "ParameterSet", + "get_empty_parameterset_mark", +] + + +old_mark_config_key = StashKey[Optional[Config]]() + + +def param( + *values: object, + marks: Union[MarkDecorator, Collection[Union[MarkDecorator, Mark]]] = (), + id: Optional[str] = None, +) -> ParameterSet: + """Specify a parameter in `pytest.mark.parametrize`_ calls or + :ref:`parametrized fixtures `. + + .. code-block:: python + + @pytest.mark.parametrize( + "test_input,expected", + [ + ("3+5", 8), + pytest.param("6*9", 42, marks=pytest.mark.xfail), + ], + ) + def test_eval(test_input, expected): + assert eval(test_input) == expected + + :param values: Variable args of the values of the parameter set, in order. + :param marks: A single mark or a list of marks to be applied to this parameter set. + :param id: The id to attribute to this parameter set. + """ + return ParameterSet.param(*values, marks=marks, id=id) + + +def pytest_addoption(parser: Parser) -> None: + group = parser.getgroup("general") + group._addoption( + "-k", + action="store", + dest="keyword", + default="", + metavar="EXPRESSION", + help="Only run tests which match the given substring expression. " + "An expression is a Python evaluatable expression " + "where all names are substring-matched against test names " + "and their parent classes. Example: -k 'test_method or test_" + "other' matches all test functions and classes whose name " + "contains 'test_method' or 'test_other', while -k 'not test_method' " + "matches those that don't contain 'test_method' in their names. " + "-k 'not test_method and not test_other' will eliminate the matches. " + "Additionally keywords are matched to classes and functions " + "containing extra names in their 'extra_keyword_matches' set, " + "as well as functions which have names assigned directly to them. " + "The matching is case-insensitive.", + ) + + group._addoption( + "-m", + action="store", + dest="markexpr", + default="", + metavar="MARKEXPR", + help="Only run tests matching given mark expression. " + "For example: -m 'mark1 and not mark2'.", + ) + + group.addoption( + "--markers", + action="store_true", + help="show markers (builtin, plugin and per-project ones).", + ) + + parser.addini("markers", "Markers for test functions", "linelist") + parser.addini(EMPTY_PARAMETERSET_OPTION, "Default marker for empty parametersets") + + +@hookimpl(tryfirst=True) +def pytest_cmdline_main(config: Config) -> Optional[Union[int, ExitCode]]: + import _pytest.config + + if config.option.markers: + config._do_configure() + tw = _pytest.config.create_terminal_writer(config) + for line in config.getini("markers"): + parts = line.split(":", 1) + name = parts[0] + rest = parts[1] if len(parts) == 2 else "" + tw.write("@pytest.mark.%s:" % name, bold=True) + tw.line(rest) + tw.line() + config._ensure_unconfigure() + return 0 + + return None + + +@dataclasses.dataclass +class KeywordMatcher: + """A matcher for keywords. + + Given a list of names, matches any substring of one of these names. The + string inclusion check is case-insensitive. + + Will match on the name of colitem, including the names of its parents. + Only matches names of items which are either a :class:`Class` or a + :class:`Function`. + + Additionally, matches on names in the 'extra_keyword_matches' set of + any item, as well as names directly assigned to test functions. + """ + + __slots__ = ("_names",) + + _names: AbstractSet[str] + + @classmethod + def from_item(cls, item: "Item") -> "KeywordMatcher": + mapped_names = set() + + # Add the names of the current item and any parent items. + import pytest + + for node in item.listchain(): + if not isinstance(node, pytest.Session): + mapped_names.add(node.name) + + # Add the names added as extra keywords to current or parent items. + mapped_names.update(item.listextrakeywords()) + + # Add the names attached to the current function through direct assignment. + function_obj = getattr(item, "function", None) + if function_obj: + mapped_names.update(function_obj.__dict__) + + # Add the markers to the keywords as we no longer handle them correctly. + mapped_names.update(mark.name for mark in item.iter_markers()) + + return cls(mapped_names) + + def __call__(self, subname: str) -> bool: + subname = subname.lower() + names = (name.lower() for name in self._names) + + for name in names: + if subname in name: + return True + return False + + +def deselect_by_keyword(items: "List[Item]", config: Config) -> None: + keywordexpr = config.option.keyword.lstrip() + if not keywordexpr: + return + + expr = _parse_expression(keywordexpr, "Wrong expression passed to '-k'") + + remaining = [] + deselected = [] + for colitem in items: + if not expr.evaluate(KeywordMatcher.from_item(colitem)): + deselected.append(colitem) + else: + remaining.append(colitem) + + if deselected: + config.hook.pytest_deselected(items=deselected) + items[:] = remaining + + +@dataclasses.dataclass +class MarkMatcher: + """A matcher for markers which are present. + + Tries to match on any marker names, attached to the given colitem. + """ + + __slots__ = ("own_mark_names",) + + own_mark_names: AbstractSet[str] + + @classmethod + def from_item(cls, item: "Item") -> "MarkMatcher": + mark_names = {mark.name for mark in item.iter_markers()} + return cls(mark_names) + + def __call__(self, name: str) -> bool: + return name in self.own_mark_names + + +def deselect_by_mark(items: "List[Item]", config: Config) -> None: + matchexpr = config.option.markexpr + if not matchexpr: + return + + expr = _parse_expression(matchexpr, "Wrong expression passed to '-m'") + remaining: List[Item] = [] + deselected: List[Item] = [] + for item in items: + if expr.evaluate(MarkMatcher.from_item(item)): + remaining.append(item) + else: + deselected.append(item) + if deselected: + config.hook.pytest_deselected(items=deselected) + items[:] = remaining + + +def _parse_expression(expr: str, exc_message: str) -> Expression: + try: + return Expression.compile(expr) + except ParseError as e: + raise UsageError(f"{exc_message}: {expr}: {e}") from None + + +def pytest_collection_modifyitems(items: "List[Item]", config: Config) -> None: + deselect_by_keyword(items, config) + deselect_by_mark(items, config) + + +def pytest_configure(config: Config) -> None: + config.stash[old_mark_config_key] = MARK_GEN._config + MARK_GEN._config = config + + empty_parameterset = config.getini(EMPTY_PARAMETERSET_OPTION) + + if empty_parameterset not in ("skip", "xfail", "fail_at_collect", None, ""): + raise UsageError( + "{!s} must be one of skip, xfail or fail_at_collect" + " but it is {!r}".format(EMPTY_PARAMETERSET_OPTION, empty_parameterset) + ) + + +def pytest_unconfigure(config: Config) -> None: + MARK_GEN._config = config.stash.get(old_mark_config_key, None) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/mark/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/mark/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b04999c5cb516c65c25b279b839f72521493579b Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/mark/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/mark/__pycache__/expression.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/mark/__pycache__/expression.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e63b86ea18c35c72954868dd644941ffdbe805d Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/mark/__pycache__/expression.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/mark/__pycache__/structures.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/mark/__pycache__/structures.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82ee0004d39cc2b2ef2cd8e964b1a6f711c70bbf Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/mark/__pycache__/structures.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/mark/expression.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/mark/expression.py new file mode 100644 index 0000000000000000000000000000000000000000..9287bcee50c59f8b750d86efc66be534804a7044 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/mark/expression.py @@ -0,0 +1,228 @@ +r"""Evaluate match expressions, as used by `-k` and `-m`. + +The grammar is: + +expression: expr? EOF +expr: and_expr ('or' and_expr)* +and_expr: not_expr ('and' not_expr)* +not_expr: 'not' not_expr | '(' expr ')' | ident +ident: (\w|:|\+|-|\.|\[|\]|\\|/)+ + +The semantics are: + +- Empty expression evaluates to False. +- ident evaluates to True of False according to a provided matcher function. +- or/and/not evaluate according to the usual boolean semantics. +""" +import ast +import dataclasses +import enum +import re +import sys +import types +from typing import Callable +from typing import Iterator +from typing import Mapping +from typing import NoReturn +from typing import Optional +from typing import Sequence + +if sys.version_info >= (3, 8): + astNameConstant = ast.Constant +else: + astNameConstant = ast.NameConstant + + +__all__ = [ + "Expression", + "ParseError", +] + + +class TokenType(enum.Enum): + LPAREN = "left parenthesis" + RPAREN = "right parenthesis" + OR = "or" + AND = "and" + NOT = "not" + IDENT = "identifier" + EOF = "end of input" + + +@dataclasses.dataclass(frozen=True) +class Token: + __slots__ = ("type", "value", "pos") + type: TokenType + value: str + pos: int + + +class ParseError(Exception): + """The expression contains invalid syntax. + + :param column: The column in the line where the error occurred (1-based). + :param message: A description of the error. + """ + + def __init__(self, column: int, message: str) -> None: + self.column = column + self.message = message + + def __str__(self) -> str: + return f"at column {self.column}: {self.message}" + + +class Scanner: + __slots__ = ("tokens", "current") + + def __init__(self, input: str) -> None: + self.tokens = self.lex(input) + self.current = next(self.tokens) + + def lex(self, input: str) -> Iterator[Token]: + pos = 0 + while pos < len(input): + if input[pos] in (" ", "\t"): + pos += 1 + elif input[pos] == "(": + yield Token(TokenType.LPAREN, "(", pos) + pos += 1 + elif input[pos] == ")": + yield Token(TokenType.RPAREN, ")", pos) + pos += 1 + else: + match = re.match(r"(:?\w|:|\+|-|\.|\[|\]|\\|/)+", input[pos:]) + if match: + value = match.group(0) + if value == "or": + yield Token(TokenType.OR, value, pos) + elif value == "and": + yield Token(TokenType.AND, value, pos) + elif value == "not": + yield Token(TokenType.NOT, value, pos) + else: + yield Token(TokenType.IDENT, value, pos) + pos += len(value) + else: + raise ParseError( + pos + 1, + f'unexpected character "{input[pos]}"', + ) + yield Token(TokenType.EOF, "", pos) + + def accept(self, type: TokenType, *, reject: bool = False) -> Optional[Token]: + if self.current.type is type: + token = self.current + if token.type is not TokenType.EOF: + self.current = next(self.tokens) + return token + if reject: + self.reject((type,)) + return None + + def reject(self, expected: Sequence[TokenType]) -> NoReturn: + raise ParseError( + self.current.pos + 1, + "expected {}; got {}".format( + " OR ".join(type.value for type in expected), + self.current.type.value, + ), + ) + + +# True, False and None are legal match expression identifiers, +# but illegal as Python identifiers. To fix this, this prefix +# is added to identifiers in the conversion to Python AST. +IDENT_PREFIX = "$" + + +def expression(s: Scanner) -> ast.Expression: + if s.accept(TokenType.EOF): + ret: ast.expr = astNameConstant(False) + else: + ret = expr(s) + s.accept(TokenType.EOF, reject=True) + return ast.fix_missing_locations(ast.Expression(ret)) + + +def expr(s: Scanner) -> ast.expr: + ret = and_expr(s) + while s.accept(TokenType.OR): + rhs = and_expr(s) + ret = ast.BoolOp(ast.Or(), [ret, rhs]) + return ret + + +def and_expr(s: Scanner) -> ast.expr: + ret = not_expr(s) + while s.accept(TokenType.AND): + rhs = not_expr(s) + ret = ast.BoolOp(ast.And(), [ret, rhs]) + return ret + + +def not_expr(s: Scanner) -> ast.expr: + if s.accept(TokenType.NOT): + return ast.UnaryOp(ast.Not(), not_expr(s)) + if s.accept(TokenType.LPAREN): + ret = expr(s) + s.accept(TokenType.RPAREN, reject=True) + return ret + ident = s.accept(TokenType.IDENT) + if ident: + return ast.Name(IDENT_PREFIX + ident.value, ast.Load()) + s.reject((TokenType.NOT, TokenType.LPAREN, TokenType.IDENT)) + + +class MatcherAdapter(Mapping[str, bool]): + """Adapts a matcher function to a locals mapping as required by eval().""" + + def __init__(self, matcher: Callable[[str], bool]) -> None: + self.matcher = matcher + + def __getitem__(self, key: str) -> bool: + return self.matcher(key[len(IDENT_PREFIX) :]) + + def __iter__(self) -> Iterator[str]: + raise NotImplementedError() + + def __len__(self) -> int: + raise NotImplementedError() + + +class Expression: + """A compiled match expression as used by -k and -m. + + The expression can be evaluated against different matchers. + """ + + __slots__ = ("code",) + + def __init__(self, code: types.CodeType) -> None: + self.code = code + + @classmethod + def compile(self, input: str) -> "Expression": + """Compile a match expression. + + :param input: The input expression - one line. + """ + astexpr = expression(Scanner(input)) + code: types.CodeType = compile( + astexpr, + filename="", + mode="eval", + ) + return Expression(code) + + def evaluate(self, matcher: Callable[[str], bool]) -> bool: + """Evaluate the match expression. + + :param matcher: + Given an identifier, should return whether it matches or not. + Should be prepared to handle arbitrary strings as input. + + :returns: Whether the expression matches or not. + """ + ret: bool = eval(self.code, {"__builtins__": {}}, MatcherAdapter(matcher)) + return ret diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/mark/structures.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/mark/structures.py new file mode 100644 index 0000000000000000000000000000000000000000..55620f0429eea3d2a635382618cb8a9e9ba19710 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/mark/structures.py @@ -0,0 +1,618 @@ +import collections.abc +import dataclasses +import inspect +import warnings +from typing import Any +from typing import Callable +from typing import Collection +from typing import Iterable +from typing import Iterator +from typing import List +from typing import Mapping +from typing import MutableMapping +from typing import NamedTuple +from typing import Optional +from typing import overload +from typing import Sequence +from typing import Set +from typing import Tuple +from typing import Type +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union + +from .._code import getfslineno +from ..compat import ascii_escaped +from ..compat import final +from ..compat import NOTSET +from ..compat import NotSetType +from _pytest.config import Config +from _pytest.deprecated import check_ispytest +from _pytest.outcomes import fail +from _pytest.warning_types import PytestUnknownMarkWarning + +if TYPE_CHECKING: + from ..nodes import Node + + +EMPTY_PARAMETERSET_OPTION = "empty_parameter_set_mark" + + +def istestfunc(func) -> bool: + return callable(func) and getattr(func, "__name__", "") != "" + + +def get_empty_parameterset_mark( + config: Config, argnames: Sequence[str], func +) -> "MarkDecorator": + from ..nodes import Collector + + fs, lineno = getfslineno(func) + reason = "got empty parameter set %r, function %s at %s:%d" % ( + argnames, + func.__name__, + fs, + lineno, + ) + + requested_mark = config.getini(EMPTY_PARAMETERSET_OPTION) + if requested_mark in ("", None, "skip"): + mark = MARK_GEN.skip(reason=reason) + elif requested_mark == "xfail": + mark = MARK_GEN.xfail(reason=reason, run=False) + elif requested_mark == "fail_at_collect": + f_name = func.__name__ + _, lineno = getfslineno(func) + raise Collector.CollectError( + "Empty parameter set in '%s' at line %d" % (f_name, lineno + 1) + ) + else: + raise LookupError(requested_mark) + return mark + + +class ParameterSet(NamedTuple): + values: Sequence[Union[object, NotSetType]] + marks: Collection[Union["MarkDecorator", "Mark"]] + id: Optional[str] + + @classmethod + def param( + cls, + *values: object, + marks: Union["MarkDecorator", Collection[Union["MarkDecorator", "Mark"]]] = (), + id: Optional[str] = None, + ) -> "ParameterSet": + if isinstance(marks, MarkDecorator): + marks = (marks,) + else: + assert isinstance(marks, collections.abc.Collection) + + if id is not None: + if not isinstance(id, str): + raise TypeError(f"Expected id to be a string, got {type(id)}: {id!r}") + id = ascii_escaped(id) + return cls(values, marks, id) + + @classmethod + def extract_from( + cls, + parameterset: Union["ParameterSet", Sequence[object], object], + force_tuple: bool = False, + ) -> "ParameterSet": + """Extract from an object or objects. + + :param parameterset: + A legacy style parameterset that may or may not be a tuple, + and may or may not be wrapped into a mess of mark objects. + + :param force_tuple: + Enforce tuple wrapping so single argument tuple values + don't get decomposed and break tests. + """ + + if isinstance(parameterset, cls): + return parameterset + if force_tuple: + return cls.param(parameterset) + else: + # TODO: Refactor to fix this type-ignore. Currently the following + # passes type-checking but crashes: + # + # @pytest.mark.parametrize(('x', 'y'), [1, 2]) + # def test_foo(x, y): pass + return cls(parameterset, marks=[], id=None) # type: ignore[arg-type] + + @staticmethod + def _parse_parametrize_args( + argnames: Union[str, Sequence[str]], + argvalues: Iterable[Union["ParameterSet", Sequence[object], object]], + *args, + **kwargs, + ) -> Tuple[Sequence[str], bool]: + if isinstance(argnames, str): + argnames = [x.strip() for x in argnames.split(",") if x.strip()] + force_tuple = len(argnames) == 1 + else: + force_tuple = False + return argnames, force_tuple + + @staticmethod + def _parse_parametrize_parameters( + argvalues: Iterable[Union["ParameterSet", Sequence[object], object]], + force_tuple: bool, + ) -> List["ParameterSet"]: + return [ + ParameterSet.extract_from(x, force_tuple=force_tuple) for x in argvalues + ] + + @classmethod + def _for_parametrize( + cls, + argnames: Union[str, Sequence[str]], + argvalues: Iterable[Union["ParameterSet", Sequence[object], object]], + func, + config: Config, + nodeid: str, + ) -> Tuple[Sequence[str], List["ParameterSet"]]: + argnames, force_tuple = cls._parse_parametrize_args(argnames, argvalues) + parameters = cls._parse_parametrize_parameters(argvalues, force_tuple) + del argvalues + + if parameters: + # Check all parameter sets have the correct number of values. + for param in parameters: + if len(param.values) != len(argnames): + msg = ( + '{nodeid}: in "parametrize" the number of names ({names_len}):\n' + " {names}\n" + "must be equal to the number of values ({values_len}):\n" + " {values}" + ) + fail( + msg.format( + nodeid=nodeid, + values=param.values, + names=argnames, + names_len=len(argnames), + values_len=len(param.values), + ), + pytrace=False, + ) + else: + # Empty parameter set (likely computed at runtime): create a single + # parameter set with NOTSET values, with the "empty parameter set" mark applied to it. + mark = get_empty_parameterset_mark(config, argnames, func) + parameters.append( + ParameterSet(values=(NOTSET,) * len(argnames), marks=[mark], id=None) + ) + return argnames, parameters + + +@final +@dataclasses.dataclass(frozen=True) +class Mark: + """A pytest mark.""" + + #: Name of the mark. + name: str + #: Positional arguments of the mark decorator. + args: Tuple[Any, ...] + #: Keyword arguments of the mark decorator. + kwargs: Mapping[str, Any] + + #: Source Mark for ids with parametrize Marks. + _param_ids_from: Optional["Mark"] = dataclasses.field(default=None, repr=False) + #: Resolved/generated ids with parametrize Marks. + _param_ids_generated: Optional[Sequence[str]] = dataclasses.field( + default=None, repr=False + ) + + def __init__( + self, + name: str, + args: Tuple[Any, ...], + kwargs: Mapping[str, Any], + param_ids_from: Optional["Mark"] = None, + param_ids_generated: Optional[Sequence[str]] = None, + *, + _ispytest: bool = False, + ) -> None: + """:meta private:""" + check_ispytest(_ispytest) + # Weirdness to bypass frozen=True. + object.__setattr__(self, "name", name) + object.__setattr__(self, "args", args) + object.__setattr__(self, "kwargs", kwargs) + object.__setattr__(self, "_param_ids_from", param_ids_from) + object.__setattr__(self, "_param_ids_generated", param_ids_generated) + + def _has_param_ids(self) -> bool: + return "ids" in self.kwargs or len(self.args) >= 4 + + def combined_with(self, other: "Mark") -> "Mark": + """Return a new Mark which is a combination of this + Mark and another Mark. + + Combines by appending args and merging kwargs. + + :param Mark other: The mark to combine with. + :rtype: Mark + """ + assert self.name == other.name + + # Remember source of ids with parametrize Marks. + param_ids_from: Optional[Mark] = None + if self.name == "parametrize": + if other._has_param_ids(): + param_ids_from = other + elif self._has_param_ids(): + param_ids_from = self + + return Mark( + self.name, + self.args + other.args, + dict(self.kwargs, **other.kwargs), + param_ids_from=param_ids_from, + _ispytest=True, + ) + + +# A generic parameter designating an object to which a Mark may +# be applied -- a test function (callable) or class. +# Note: a lambda is not allowed, but this can't be represented. +Markable = TypeVar("Markable", bound=Union[Callable[..., object], type]) + + +@dataclasses.dataclass +class MarkDecorator: + """A decorator for applying a mark on test functions and classes. + + ``MarkDecorators`` are created with ``pytest.mark``:: + + mark1 = pytest.mark.NAME # Simple MarkDecorator + mark2 = pytest.mark.NAME(name1=value) # Parametrized MarkDecorator + + and can then be applied as decorators to test functions:: + + @mark2 + def test_function(): + pass + + When a ``MarkDecorator`` is called, it does the following: + + 1. If called with a single class as its only positional argument and no + additional keyword arguments, it attaches the mark to the class so it + gets applied automatically to all test cases found in that class. + + 2. If called with a single function as its only positional argument and + no additional keyword arguments, it attaches the mark to the function, + containing all the arguments already stored internally in the + ``MarkDecorator``. + + 3. When called in any other case, it returns a new ``MarkDecorator`` + instance with the original ``MarkDecorator``'s content updated with + the arguments passed to this call. + + Note: The rules above prevent a ``MarkDecorator`` from storing only a + single function or class reference as its positional argument with no + additional keyword or positional arguments. You can work around this by + using `with_args()`. + """ + + mark: Mark + + def __init__(self, mark: Mark, *, _ispytest: bool = False) -> None: + """:meta private:""" + check_ispytest(_ispytest) + self.mark = mark + + @property + def name(self) -> str: + """Alias for mark.name.""" + return self.mark.name + + @property + def args(self) -> Tuple[Any, ...]: + """Alias for mark.args.""" + return self.mark.args + + @property + def kwargs(self) -> Mapping[str, Any]: + """Alias for mark.kwargs.""" + return self.mark.kwargs + + @property + def markname(self) -> str: + """:meta private:""" + return self.name # for backward-compat (2.4.1 had this attr) + + def with_args(self, *args: object, **kwargs: object) -> "MarkDecorator": + """Return a MarkDecorator with extra arguments added. + + Unlike calling the MarkDecorator, with_args() can be used even + if the sole argument is a callable/class. + """ + mark = Mark(self.name, args, kwargs, _ispytest=True) + return MarkDecorator(self.mark.combined_with(mark), _ispytest=True) + + # Type ignored because the overloads overlap with an incompatible + # return type. Not much we can do about that. Thankfully mypy picks + # the first match so it works out even if we break the rules. + @overload + def __call__(self, arg: Markable) -> Markable: # type: ignore[misc] + pass + + @overload + def __call__(self, *args: object, **kwargs: object) -> "MarkDecorator": + pass + + def __call__(self, *args: object, **kwargs: object): + """Call the MarkDecorator.""" + if args and not kwargs: + func = args[0] + is_class = inspect.isclass(func) + if len(args) == 1 and (istestfunc(func) or is_class): + store_mark(func, self.mark) + return func + return self.with_args(*args, **kwargs) + + +def get_unpacked_marks( + obj: Union[object, type], + *, + consider_mro: bool = True, +) -> List[Mark]: + """Obtain the unpacked marks that are stored on an object. + + If obj is a class and consider_mro is true, return marks applied to + this class and all of its super-classes in MRO order. If consider_mro + is false, only return marks applied directly to this class. + """ + if isinstance(obj, type): + if not consider_mro: + mark_lists = [obj.__dict__.get("pytestmark", [])] + else: + mark_lists = [ + x.__dict__.get("pytestmark", []) for x in reversed(obj.__mro__) + ] + mark_list = [] + for item in mark_lists: + if isinstance(item, list): + mark_list.extend(item) + else: + mark_list.append(item) + else: + mark_attribute = getattr(obj, "pytestmark", []) + if isinstance(mark_attribute, list): + mark_list = mark_attribute + else: + mark_list = [mark_attribute] + return list(normalize_mark_list(mark_list)) + + +def normalize_mark_list( + mark_list: Iterable[Union[Mark, MarkDecorator]] +) -> Iterable[Mark]: + """ + Normalize an iterable of Mark or MarkDecorator objects into a list of marks + by retrieving the `mark` attribute on MarkDecorator instances. + + :param mark_list: marks to normalize + :returns: A new list of the extracted Mark objects + """ + for mark in mark_list: + mark_obj = getattr(mark, "mark", mark) + if not isinstance(mark_obj, Mark): + raise TypeError(f"got {repr(mark_obj)} instead of Mark") + yield mark_obj + + +def store_mark(obj, mark: Mark) -> None: + """Store a Mark on an object. + + This is used to implement the Mark declarations/decorators correctly. + """ + assert isinstance(mark, Mark), mark + # Always reassign name to avoid updating pytestmark in a reference that + # was only borrowed. + obj.pytestmark = [*get_unpacked_marks(obj, consider_mro=False), mark] + + +# Typing for builtin pytest marks. This is cheating; it gives builtin marks +# special privilege, and breaks modularity. But practicality beats purity... +if TYPE_CHECKING: + from _pytest.scope import _ScopeName + + class _SkipMarkDecorator(MarkDecorator): + @overload # type: ignore[override,misc,no-overload-impl] + def __call__(self, arg: Markable) -> Markable: + ... + + @overload + def __call__(self, reason: str = ...) -> "MarkDecorator": + ... + + class _SkipifMarkDecorator(MarkDecorator): + def __call__( # type: ignore[override] + self, + condition: Union[str, bool] = ..., + *conditions: Union[str, bool], + reason: str = ..., + ) -> MarkDecorator: + ... + + class _XfailMarkDecorator(MarkDecorator): + @overload # type: ignore[override,misc,no-overload-impl] + def __call__(self, arg: Markable) -> Markable: + ... + + @overload + def __call__( + self, + condition: Union[str, bool] = ..., + *conditions: Union[str, bool], + reason: str = ..., + run: bool = ..., + raises: Union[Type[BaseException], Tuple[Type[BaseException], ...]] = ..., + strict: bool = ..., + ) -> MarkDecorator: + ... + + class _ParametrizeMarkDecorator(MarkDecorator): + def __call__( # type: ignore[override] + self, + argnames: Union[str, Sequence[str]], + argvalues: Iterable[Union[ParameterSet, Sequence[object], object]], + *, + indirect: Union[bool, Sequence[str]] = ..., + ids: Optional[ + Union[ + Iterable[Union[None, str, float, int, bool]], + Callable[[Any], Optional[object]], + ] + ] = ..., + scope: Optional[_ScopeName] = ..., + ) -> MarkDecorator: + ... + + class _UsefixturesMarkDecorator(MarkDecorator): + def __call__(self, *fixtures: str) -> MarkDecorator: # type: ignore[override] + ... + + class _FilterwarningsMarkDecorator(MarkDecorator): + def __call__(self, *filters: str) -> MarkDecorator: # type: ignore[override] + ... + + +@final +class MarkGenerator: + """Factory for :class:`MarkDecorator` objects - exposed as + a ``pytest.mark`` singleton instance. + + Example:: + + import pytest + + @pytest.mark.slowtest + def test_function(): + pass + + applies a 'slowtest' :class:`Mark` on ``test_function``. + """ + + # See TYPE_CHECKING above. + if TYPE_CHECKING: + skip: _SkipMarkDecorator + skipif: _SkipifMarkDecorator + xfail: _XfailMarkDecorator + parametrize: _ParametrizeMarkDecorator + usefixtures: _UsefixturesMarkDecorator + filterwarnings: _FilterwarningsMarkDecorator + + def __init__(self, *, _ispytest: bool = False) -> None: + check_ispytest(_ispytest) + self._config: Optional[Config] = None + self._markers: Set[str] = set() + + def __getattr__(self, name: str) -> MarkDecorator: + """Generate a new :class:`MarkDecorator` with the given name.""" + if name[0] == "_": + raise AttributeError("Marker name must NOT start with underscore") + + if self._config is not None: + # We store a set of markers as a performance optimisation - if a mark + # name is in the set we definitely know it, but a mark may be known and + # not in the set. We therefore start by updating the set! + if name not in self._markers: + for line in self._config.getini("markers"): + # example lines: "skipif(condition): skip the given test if..." + # or "hypothesis: tests which use Hypothesis", so to get the + # marker name we split on both `:` and `(`. + marker = line.split(":")[0].split("(")[0].strip() + self._markers.add(marker) + + # If the name is not in the set of known marks after updating, + # then it really is time to issue a warning or an error. + if name not in self._markers: + if self._config.option.strict_markers or self._config.option.strict: + fail( + f"{name!r} not found in `markers` configuration option", + pytrace=False, + ) + + # Raise a specific error for common misspellings of "parametrize". + if name in ["parameterize", "parametrise", "parameterise"]: + __tracebackhide__ = True + fail(f"Unknown '{name}' mark, did you mean 'parametrize'?") + + warnings.warn( + "Unknown pytest.mark.%s - is this a typo? You can register " + "custom marks to avoid this warning - for details, see " + "https://docs.pytest.org/en/stable/how-to/mark.html" % name, + PytestUnknownMarkWarning, + 2, + ) + + return MarkDecorator(Mark(name, (), {}, _ispytest=True), _ispytest=True) + + +MARK_GEN = MarkGenerator(_ispytest=True) + + +@final +class NodeKeywords(MutableMapping[str, Any]): + __slots__ = ("node", "parent", "_markers") + + def __init__(self, node: "Node") -> None: + self.node = node + self.parent = node.parent + self._markers = {node.name: True} + + def __getitem__(self, key: str) -> Any: + try: + return self._markers[key] + except KeyError: + if self.parent is None: + raise + return self.parent.keywords[key] + + def __setitem__(self, key: str, value: Any) -> None: + self._markers[key] = value + + # Note: we could've avoided explicitly implementing some of the methods + # below and use the collections.abc fallback, but that would be slow. + + def __contains__(self, key: object) -> bool: + return ( + key in self._markers + or self.parent is not None + and key in self.parent.keywords + ) + + def update( # type: ignore[override] + self, + other: Union[Mapping[str, Any], Iterable[Tuple[str, Any]]] = (), + **kwds: Any, + ) -> None: + self._markers.update(other) + self._markers.update(kwds) + + def __delitem__(self, key: str) -> None: + raise ValueError("cannot delete key in keywords dict") + + def __iter__(self) -> Iterator[str]: + # Doesn't need to be fast. + yield from self._markers + if self.parent is not None: + for keyword in self.parent.keywords: + # self._marks and self.parent.keywords can have duplicates. + if keyword not in self._markers: + yield keyword + + def __len__(self) -> int: + # Doesn't need to be fast. + return sum(1 for keyword in self) + + def __repr__(self) -> str: + return f"" diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiosignal-1.4.0.dist-info/licenses/LICENSE b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiosignal-1.4.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..7082a2d5b9047bfc09589f387053e24ea490bc54 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiosignal-1.4.0.dist-info/licenses/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2013-2019 Nikolay Kim and Andrew Svetlov + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiosignal/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiosignal/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20ddba0955ff65fa0c0718e01094b8d9dac33a58 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiosignal/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c989ded69638a9e580be7639db0b01ed1eef01ab Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/application_info.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/application_info.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13fdac6bd96b09a85fee10373650d5cf0990a8b6 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/application_info.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/auth.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/auth.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b8af722a28f9f5fd42aa9c251c2a4374260b657 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/auth.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/cluster.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/cluster.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1d282f3d537441e94eb59cc8c641ae788bd9c03 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/cluster.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:79ac53bd3da2d3c47e1aecf0f38fc1540978bfd669fcb574a765eed1a542518f +size 239959 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/concurrent.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/concurrent.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84dec96da56faef81a0ae7517304ac263630a8c5 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/concurrent.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/connection.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/connection.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11e74cde14b2e0a33481ee926b089a96c1bc1c19 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/connection.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/cqltypes.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/cqltypes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88ecdac007347ac730a6a2c1b653a82088ab90f1 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/cqltypes.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/cython_deps.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/cython_deps.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2df6d765d87b60e653aa85821074775e6339e3d3 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/cython_deps.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/encoder.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/encoder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55f482a7e618d4f06c46fa2554b5331a26cdff9d Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/encoder.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/marshal.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/marshal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2731202dd58b8a8f696ea4f6621f2243a2079753 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/marshal.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/metadata.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/metadata.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..552b8df7f0db93ac2963f72abd1733b2c988cb5c --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/metadata.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:987d25f176572f36045e4d2db189ec7ce53c9a4e1ef7e8164b9c8f0e10690e09 +size 154637 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/metrics.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/metrics.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe21ce14dff6e4ececa67670d18575de9f06fac1 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/metrics.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/murmur3.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/murmur3.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78638c87a41e4ebf7c10416dca61a5fb738d2caa Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/murmur3.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/policies.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/policies.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c32169cd74393b781156075606d7b1f3f37558cf Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/policies.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/pool.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/pool.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35d5a0cfd3cdba27639676052d2836f87c8e2ee0 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/pool.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/protocol.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/protocol.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f495f21c6c8e6698a86ce487ba13717a5cf1157e Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/protocol.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/protocol_features.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/protocol_features.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d587ca43089831b473e3af228aa6ac0347655c8 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/protocol_features.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/query.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/query.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3df5d8ea24e687807475d465c334aa0be98e4189 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/query.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/segment.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/segment.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b2caf9a36215830e108ea9d709617af8f96de8a Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/segment.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/shard_info.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/shard_info.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae7a60d6e219fa6cbd6428c208cf10bfb8f309f3 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/shard_info.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/tablets.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/tablets.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10b3a5d2fbab623e3a632f43ba01fdfa61ae698e Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/tablets.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/timestamps.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/timestamps.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eee00db5eb6e13ffa1d1289085587f9f5b53a4fe Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/timestamps.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/type_codes.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/type_codes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b6a9c8b28da20bdacc445b77ec06eba2c61b2b5 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/type_codes.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/util.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8dd00c616d451667f31107a5fe0887bf298bd02d Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/__pycache__/util.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/column_encryption/_policies.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/column_encryption/_policies.py new file mode 100644 index 0000000000000000000000000000000000000000..ef8097bfbd6958a38ff534c0fc2fde10d67f534b --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/column_encryption/_policies.py @@ -0,0 +1,139 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from collections import namedtuple +from functools import lru_cache + +import logging +import os + +log = logging.getLogger(__name__) + +from cassandra.cqltypes import _cqltypes +from cassandra.policies import ColumnEncryptionPolicy + +from cryptography.hazmat.primitives import padding +from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + +AES256_BLOCK_SIZE = 128 +AES256_BLOCK_SIZE_BYTES = int(AES256_BLOCK_SIZE / 8) +AES256_KEY_SIZE = 256 +AES256_KEY_SIZE_BYTES = int(AES256_KEY_SIZE / 8) + +ColData = namedtuple('ColData', ['key','type']) + +class AES256ColumnEncryptionPolicy(ColumnEncryptionPolicy): + + # Fix block cipher mode for now. IV size is a function of block cipher used + # so fixing this avoids (possibly unnecessary) validation logic here. + mode = modes.CBC + + # "iv" param here expects a bytearray that's the same size as the block + # size for AES-256 (128 bits or 16 bytes). If none is provided a new one + # will be randomly generated, but in this case the IV should be recorded and + # preserved or else you will not be able to decrypt any data encrypted by this + # policy. + def __init__(self, iv=None): + + # CBC uses an IV that's the same size as the block size + # + # Avoid defining IV with a default arg in order to stay away from + # any issues around the caching of default args + self.iv = iv + if self.iv: + if not len(self.iv) == AES256_BLOCK_SIZE_BYTES: + raise ValueError("This policy uses AES-256 with CBC mode and therefore expects a 128-bit initialization vector") + else: + self.iv = os.urandom(AES256_BLOCK_SIZE_BYTES) + + # ColData for a given ColDesc is always preserved. We only create a Cipher + # when there's an actual need to for a given ColDesc + self.coldata = {} + self.ciphers = {} + + def encrypt(self, coldesc, obj_bytes): + + # AES256 has a 128-bit block size so if the input bytes don't align perfectly on + # those blocks we have to pad them. There's plenty of room for optimization here: + # + # * Instances of the PKCS7 padder should be managed in a bounded pool + # * It would be nice if we could get a flag from encrypted data to indicate + # whether it was padded or not + # * Might be able to make this happen with a leading block of flags in encrypted data + padder = padding.PKCS7(AES256_BLOCK_SIZE).padder() + padded_bytes = padder.update(obj_bytes) + padder.finalize() + + cipher = self._get_cipher(coldesc) + encryptor = cipher.encryptor() + return self.iv + encryptor.update(padded_bytes) + encryptor.finalize() + + def decrypt(self, coldesc, bytes): + + iv = bytes[:AES256_BLOCK_SIZE_BYTES] + encrypted_bytes = bytes[AES256_BLOCK_SIZE_BYTES:] + cipher = self._get_cipher(coldesc, iv=iv) + decryptor = cipher.decryptor() + padded_bytes = decryptor.update(encrypted_bytes) + decryptor.finalize() + + unpadder = padding.PKCS7(AES256_BLOCK_SIZE).unpadder() + return unpadder.update(padded_bytes) + unpadder.finalize() + + def add_column(self, coldesc, key, type): + + if not coldesc: + raise ValueError("ColDesc supplied to add_column cannot be None") + if not key: + raise ValueError("Key supplied to add_column cannot be None") + if not type: + raise ValueError("Type supplied to add_column cannot be None") + if type not in _cqltypes.keys(): + raise ValueError("Type %s is not a supported type".format(type)) + if not len(key) == AES256_KEY_SIZE_BYTES: + raise ValueError("AES256 column encryption policy expects a 256-bit encryption key") + self.coldata[coldesc] = ColData(key, _cqltypes[type]) + + def contains_column(self, coldesc): + return coldesc in self.coldata + + def encode_and_encrypt(self, coldesc, obj): + if not coldesc: + raise ValueError("ColDesc supplied to encode_and_encrypt cannot be None") + if not obj: + raise ValueError("Object supplied to encode_and_encrypt cannot be None") + coldata = self.coldata.get(coldesc) + if not coldata: + raise ValueError("Could not find ColData for ColDesc %s".format(coldesc)) + return self.encrypt(coldesc, coldata.type.serialize(obj, None)) + + def cache_info(self): + return AES256ColumnEncryptionPolicy._build_cipher.cache_info() + + def column_type(self, coldesc): + return self.coldata[coldesc].type + + def _get_cipher(self, coldesc, iv=None): + """ + Access relevant state from this instance necessary to create a Cipher and then get one, + hopefully returning a cached instance if we've already done so (and it hasn't been evicted) + """ + try: + coldata = self.coldata[coldesc] + return AES256ColumnEncryptionPolicy._build_cipher(coldata.key, iv or self.iv) + except KeyError: + raise ValueError("Could not find column {}".format(coldesc)) + + # Explicitly use a class method here to avoid caching self + @lru_cache(maxsize=128) + def _build_cipher(key, iv): + return Cipher(algorithms.AES256(key), AES256ColumnEncryptionPolicy.mode(iv)) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/column_encryption/policies.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/column_encryption/policies.py new file mode 100644 index 0000000000000000000000000000000000000000..770084bd482ecd054e21aa768abaf1454ca841a6 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/column_encryption/policies.py @@ -0,0 +1,20 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +try: + import cryptography + from cassandra.column_encryption._policies import * +except ImportError: + # Cryptography is not installed + pass diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b9466e961b9ee4e538f6860db31a9cf81b994ff2 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/__init__.py @@ -0,0 +1,31 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Caching constants. +CACHING_ALL = "ALL" +CACHING_KEYS_ONLY = "KEYS_ONLY" +CACHING_ROWS_ONLY = "ROWS_ONLY" +CACHING_NONE = "NONE" + + +class CQLEngineException(Exception): + pass + + +class ValidationError(CQLEngineException): + pass + + +class UnicodeMixin(object): + __str__ = lambda x: x.__unicode__() diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/columns.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/columns.py new file mode 100644 index 0000000000000000000000000000000000000000..3d85587524a4e67ea370abc89e7be72b4d8134d7 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/columns.py @@ -0,0 +1,1077 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from copy import deepcopy, copy +from datetime import date, datetime, timedelta, timezone +import logging +from uuid import UUID as _UUID + +from cassandra import util +from cassandra.cqltypes import SimpleDateType, _cqltypes, UserType +from cassandra.cqlengine import ValidationError +from cassandra.cqlengine.functions import get_total_seconds +from cassandra.util import Duration as _Duration + +log = logging.getLogger(__name__) + + +class BaseValueManager(object): + + def __init__(self, instance, column, value): + self.instance = instance + self.column = column + self.value = value + self.previous_value = None + self.explicit = False + + @property + def deleted(self): + return self.column._val_is_null(self.value) and (self.explicit or not self.column._val_is_null(self.previous_value)) + + @property + def changed(self): + """ + Indicates whether or not this value has changed. + + :rtype: boolean + + """ + if self.explicit: + return self.value != self.previous_value + + if isinstance(self.column, BaseContainerColumn): + default_value = self.column.get_default() + if self.column._val_is_null(default_value): + return not self.column._val_is_null(self.value) and self.value != self.previous_value + elif self.previous_value is None: + return self.value != default_value + + return self.value != self.previous_value + + return False + + def reset_previous_value(self): + self.previous_value = deepcopy(self.value) + + def getval(self): + return self.value + + def setval(self, val): + self.value = val + self.explicit = True + + def delval(self): + self.value = None + + def get_property(self): + _get = lambda slf: self.getval() + _set = lambda slf, val: self.setval(val) + _del = lambda slf: self.delval() + + if self.column.can_delete: + return property(_get, _set, _del) + else: + return property(_get, _set) + + +class Column(object): + + # the cassandra type this column maps to + db_type = None + value_manager = BaseValueManager + + instance_counter = 0 + + _python_type_hashable = True + + primary_key = False + """ + bool flag, indicates this column is a primary key. The first primary key defined + on a model is the partition key (unless partition keys are set), all others are cluster keys + """ + + partition_key = False + + """ + indicates that this column should be the partition key, defining + more than one partition key column creates a compound partition key + """ + + index = False + """ + bool flag, indicates an index should be created for this column + """ + + custom_index = False + """ + bool flag, indicates an index is managed outside of cqlengine. This is + useful if you want to do filter queries on fields that have custom + indexes. + """ + + db_field = None + """ + the fieldname this field will map to in the database + """ + + default = None + """ + the default value, can be a value or a callable (no args) + """ + + required = False + """ + boolean, is the field required? Model validation will raise and + exception if required is set to True and there is a None value assigned + """ + + clustering_order = None + """ + only applicable on clustering keys (primary keys that are not partition keys) + determines the order that the clustering keys are sorted on disk + """ + + discriminator_column = False + """ + boolean, if set to True, this column will be used for discriminating records + of inherited models. + + Should only be set on a column of an abstract model being used for inheritance. + + There may only be one discriminator column per model. See :attr:`~.__discriminator_value__` + for how to specify the value of this column on specialized models. + """ + + static = False + """ + boolean, if set to True, this is a static column, with a single value per partition + """ + + def __init__(self, + primary_key=False, + partition_key=False, + index=False, + db_field=None, + default=None, + required=False, + clustering_order=None, + discriminator_column=False, + static=False, + custom_index=False): + self.partition_key = partition_key + self.primary_key = partition_key or primary_key + self.index = index + self.custom_index = custom_index + self.db_field = db_field + self.default = default + self.required = required + self.clustering_order = clustering_order + self.discriminator_column = discriminator_column + + # the column name in the model definition + self.column_name = None + self._partition_key_index = None + self.static = static + + self.value = None + + # keep track of instantiation order + self.position = Column.instance_counter + Column.instance_counter += 1 + + def __ne__(self, other): + if isinstance(other, Column): + return self.position != other.position + return NotImplemented + + def __eq__(self, other): + if isinstance(other, Column): + return self.position == other.position + return NotImplemented + + def __lt__(self, other): + if isinstance(other, Column): + return self.position < other.position + return NotImplemented + + def __le__(self, other): + if isinstance(other, Column): + return self.position <= other.position + return NotImplemented + + def __gt__(self, other): + if isinstance(other, Column): + return self.position > other.position + return NotImplemented + + def __ge__(self, other): + if isinstance(other, Column): + return self.position >= other.position + return NotImplemented + + def __hash__(self): + return id(self) + + def validate(self, value): + """ + Returns a cleaned and validated value. Raises a ValidationError + if there's a problem + """ + if value is None: + if self.required: + raise ValidationError('{0} - None values are not allowed'.format(self.column_name or self.db_field)) + return value + + def to_python(self, value): + """ + Converts data from the database into python values + raises a ValidationError if the value can't be converted + """ + return value + + def to_database(self, value): + """ + Converts python value into database value + """ + return value + + @property + def has_default(self): + return self.default is not None + + @property + def is_primary_key(self): + return self.primary_key + + @property + def can_delete(self): + return not self.primary_key + + def get_default(self): + if self.has_default: + if callable(self.default): + return self.default() + else: + return self.default + + def get_column_def(self): + """ + Returns a column definition for CQL table definition + """ + static = "static" if self.static else "" + return '{0} {1} {2}'.format(self.cql, self.db_type, static) + + # TODO: make columns use cqltypes under the hood + # until then, this bridges the gap in using types along with cassandra.metadata for CQL generation + def cql_parameterized_type(self): + return self.db_type + + def set_column_name(self, name): + """ + Sets the column name during document class construction + This value will be ignored if db_field is set in __init__ + """ + self.column_name = name + + @property + def db_field_name(self): + """ Returns the name of the cql name of this column """ + return self.db_field if self.db_field is not None else self.column_name + + @property + def db_index_name(self): + """ Returns the name of the cql index """ + return 'index_{0}'.format(self.db_field_name) + + @property + def has_index(self): + return self.index or self.custom_index + + @property + def cql(self): + return self.get_cql() + + def get_cql(self): + return '"{0}"'.format(self.db_field_name) + + def _val_is_null(self, val): + """ determines if the given value equates to a null value for the given column type """ + return val is None + + @property + def sub_types(self): + return [] + + @property + def cql_type(self): + return _cqltypes[self.db_type] + + +class Blob(Column): + """ + Stores a raw binary value + """ + db_type = 'blob' + + def to_database(self, value): + + if not isinstance(value, (bytes, bytearray)): + raise Exception("expecting a binary, got a %s" % type(value)) + + val = super(Bytes, self).to_database(value) + return bytearray(val) + + +Bytes = Blob + + +class Inet(Column): + """ + Stores an IP address in IPv4 or IPv6 format + """ + db_type = 'inet' + + +class Text(Column): + """ + Stores a UTF-8 encoded string + """ + db_type = 'text' + + def __init__(self, min_length=None, max_length=None, **kwargs): + """ + :param int min_length: Sets the minimum length of this string, for validation purposes. + Defaults to 1 if this is a ``required`` column. Otherwise, None. + :param int max_length: Sets the maximum length of this string, for validation purposes. + """ + self.min_length = ( + 1 if min_length is None and kwargs.get('required', False) + else min_length) + self.max_length = max_length + + if self.min_length is not None: + if self.min_length < 0: + raise ValueError( + 'Minimum length is not allowed to be negative.') + + if self.max_length is not None: + if self.max_length < 0: + raise ValueError( + 'Maximum length is not allowed to be negative.') + + if self.min_length is not None and self.max_length is not None: + if self.max_length < self.min_length: + raise ValueError( + 'Maximum length must be greater or equal ' + 'to minimum length.') + + super(Text, self).__init__(**kwargs) + + def validate(self, value): + value = super(Text, self).validate(value) + if not isinstance(value, (str, bytearray)) and value is not None: + raise ValidationError('{0} {1} is not a string'.format(self.column_name, type(value))) + if self.max_length is not None: + if value and len(value) > self.max_length: + raise ValidationError('{0} is longer than {1} characters'.format(self.column_name, self.max_length)) + if self.min_length: + if (self.min_length and not value) or len(value) < self.min_length: + raise ValidationError('{0} is shorter than {1} characters'.format(self.column_name, self.min_length)) + return value + + +class Ascii(Text): + """ + Stores a US-ASCII character string + """ + db_type = 'ascii' + + def validate(self, value): + """ Only allow ASCII and None values. + + Check against US-ASCII, a.k.a. 7-bit ASCII, a.k.a. ISO646-US, a.k.a. + the Basic Latin block of the Unicode character set. + + Source: https://github.com/apache/cassandra/blob + /3dcbe90e02440e6ee534f643c7603d50ca08482b/src/java/org/apache/cassandra + /serializers/AsciiSerializer.java#L29 + """ + value = super(Ascii, self).validate(value) + if value: + charset = value if isinstance( + value, (bytearray, )) else map(ord, value) + if not set(range(128)).issuperset(charset): + raise ValidationError( + '{!r} is not an ASCII string.'.format(value)) + return value + + +class Integer(Column): + """ + Stores a 32-bit signed integer value + """ + + db_type = 'int' + + def validate(self, value): + val = super(Integer, self).validate(value) + if val is None: + return + try: + return int(val) + except (TypeError, ValueError): + raise ValidationError("{0} {1} can't be converted to integral value".format(self.column_name, value)) + + def to_python(self, value): + return self.validate(value) + + def to_database(self, value): + return self.validate(value) + + +class TinyInt(Integer): + """ + Stores an 8-bit signed integer value + + .. versionadded:: 2.6.0 + + requires C* 2.2+ and protocol v4+ + """ + db_type = 'tinyint' + + +class SmallInt(Integer): + """ + Stores a 16-bit signed integer value + + .. versionadded:: 2.6.0 + + requires C* 2.2+ and protocol v4+ + """ + db_type = 'smallint' + + +class BigInt(Integer): + """ + Stores a 64-bit signed integer value + """ + db_type = 'bigint' + + +class VarInt(Column): + """ + Stores an arbitrary-precision integer + """ + db_type = 'varint' + + def validate(self, value): + val = super(VarInt, self).validate(value) + if val is None: + return + try: + return int(val) + except (TypeError, ValueError): + raise ValidationError( + "{0} {1} can't be converted to integral value".format(self.column_name, value)) + + def to_python(self, value): + return self.validate(value) + + def to_database(self, value): + return self.validate(value) + + +class CounterValueManager(BaseValueManager): + def __init__(self, instance, column, value): + super(CounterValueManager, self).__init__(instance, column, value) + self.value = self.value or 0 + self.previous_value = self.previous_value or 0 + + +class Counter(Integer): + """ + Stores a counter that can be incremented and decremented + """ + db_type = 'counter' + + value_manager = CounterValueManager + + def __init__(self, + index=False, + db_field=None, + required=False): + super(Counter, self).__init__( + primary_key=False, + partition_key=False, + index=index, + db_field=db_field, + default=0, + required=required, + ) + + +class DateTime(Column): + """ + Stores a datetime value + """ + db_type = 'timestamp' + + truncate_microseconds = False + """ + Set this ``True`` to have model instances truncate the date, quantizing it in the same way it will be in the database. + This allows equality comparison between assigned values and values read back from the database:: + + DateTime.truncate_microseconds = True + assert Model.create(id=0, d=datetime.utcnow()) == Model.objects(id=0).first() + + Defaults to ``False`` to preserve legacy behavior. May change in the future. + """ + + def to_python(self, value): + if value is None: + return + if isinstance(value, datetime): + if DateTime.truncate_microseconds: + us = value.microsecond + truncated_us = us // 1000 * 1000 + return value - timedelta(microseconds=us - truncated_us) + else: + return value + elif isinstance(value, date): + return datetime(*(value.timetuple()[:6])) + + return datetime.fromtimestamp(value, tz=timezone.utc).replace(tzinfo=None) + + def to_database(self, value): + value = super(DateTime, self).to_database(value) + if value is None: + return + if not isinstance(value, datetime): + if isinstance(value, date): + value = datetime(value.year, value.month, value.day) + else: + raise ValidationError("{0} '{1}' is not a datetime object".format(self.column_name, value)) + epoch = datetime(1970, 1, 1, tzinfo=value.tzinfo) + offset = get_total_seconds(epoch.tzinfo.utcoffset(epoch)) if epoch.tzinfo else 0 + + return int((get_total_seconds(value - epoch) - offset) * 1000) + + +class Date(Column): + """ + Stores a simple date, with no time-of-day + + .. versionchanged:: 2.6.0 + + removed overload of Date and DateTime. DateTime is a drop-in replacement for legacy models + + requires C* 2.2+ and protocol v4+ + """ + db_type = 'date' + + def to_database(self, value): + if value is None: + return + + # need to translate to int version because some dates are not representable in + # string form (datetime limitation) + d = value if isinstance(value, util.Date) else util.Date(value) + return d.days_from_epoch + SimpleDateType.EPOCH_OFFSET_DAYS + + def to_python(self, value): + if value is None: + return + if isinstance(value, util.Date): + return value + if isinstance(value, datetime): + value = value.date() + return util.Date(value) + +class Time(Column): + """ + Stores a timezone-naive time-of-day, with nanosecond precision + + .. versionadded:: 2.6.0 + + requires C* 2.2+ and protocol v4+ + """ + db_type = 'time' + + def to_database(self, value): + value = super(Time, self).to_database(value) + if value is None: + return + # str(util.Time) yields desired CQL encoding + return value if isinstance(value, util.Time) else util.Time(value) + + def to_python(self, value): + value = super(Time, self).to_database(value) + if value is None: + return + if isinstance(value, util.Time): + return value + return util.Time(value) + +class Duration(Column): + """ + Stores a duration (months, days, nanoseconds) + + .. versionadded:: 3.10.0 + + requires C* 3.10+ and protocol v4+ + """ + db_type = 'duration' + + def validate(self, value): + val = super(Duration, self).validate(value) + if val is None: + return + if not isinstance(val, _Duration): + raise TypeError('{0} {1} is not a valid Duration.'.format(self.column_name, value)) + return val + + +class UUID(Column): + """ + Stores a type 1 or 4 UUID + """ + db_type = 'uuid' + + def validate(self, value): + val = super(UUID, self).validate(value) + if val is None: + return + if isinstance(val, _UUID): + return val + if isinstance(val, str): + try: + return _UUID(val) + except ValueError: + # fall-through to error + pass + raise ValidationError("{0} {1} is not a valid uuid".format( + self.column_name, value)) + + def to_python(self, value): + return self.validate(value) + + def to_database(self, value): + return self.validate(value) + + +class TimeUUID(UUID): + """ + UUID containing timestamp + """ + + db_type = 'timeuuid' + + +class Boolean(Column): + """ + Stores a boolean True or False value + """ + db_type = 'boolean' + + def validate(self, value): + """ Always returns a Python boolean. """ + value = super(Boolean, self).validate(value) + + if value is not None: + value = bool(value) + + return value + + def to_python(self, value): + return self.validate(value) + + +class BaseFloat(Column): + def validate(self, value): + value = super(BaseFloat, self).validate(value) + if value is None: + return + try: + return float(value) + except (TypeError, ValueError): + raise ValidationError("{0} {1} is not a valid float".format(self.column_name, value)) + + def to_python(self, value): + return self.validate(value) + + def to_database(self, value): + return self.validate(value) + + +class Float(BaseFloat): + """ + Stores a single-precision floating-point value + """ + db_type = 'float' + + +class Double(BaseFloat): + """ + Stores a double-precision floating-point value + """ + db_type = 'double' + + +class Decimal(Column): + """ + Stores a variable precision decimal value + """ + db_type = 'decimal' + + def validate(self, value): + from decimal import Decimal as _Decimal + from decimal import InvalidOperation + val = super(Decimal, self).validate(value) + if val is None: + return + try: + return _Decimal(repr(val)) if isinstance(val, float) else _Decimal(val) + except InvalidOperation: + raise ValidationError("{0} '{1}' can't be coerced to decimal".format(self.column_name, val)) + + def to_python(self, value): + return self.validate(value) + + def to_database(self, value): + return self.validate(value) + + +class BaseCollectionColumn(Column): + """ + Base Container type for collection-like columns. + + http://cassandra.apache.org/doc/cql3/CQL-3.0.html#collections + """ + def __init__(self, types, **kwargs): + """ + :param types: a sequence of sub types in this collection + """ + instances = [] + for t in types: + inheritance_comparator = issubclass if isinstance(t, type) else isinstance + if not inheritance_comparator(t, Column): + raise ValidationError("%s is not a column class" % (t,)) + if t.db_type is None: + raise ValidationError("%s is an abstract type" % (t,)) + inst = t() if isinstance(t, type) else t + if isinstance(t, BaseCollectionColumn): + inst._freeze_db_type() + instances.append(inst) + + self.types = instances + super(BaseCollectionColumn, self).__init__(**kwargs) + + def validate(self, value): + value = super(BaseCollectionColumn, self).validate(value) + # It is dangerous to let collections have more than 65535. + # See: https://issues.apache.org/jira/browse/CASSANDRA-5428 + if value is not None and len(value) > 65535: + raise ValidationError("{0} Collection can't have more than 65535 elements.".format(self.column_name)) + return value + + def _val_is_null(self, val): + return not val + + def _freeze_db_type(self): + if not self.db_type.startswith('frozen'): + self.db_type = "frozen<%s>" % (self.db_type,) + + @property + def sub_types(self): + return self.types + + @property + def cql_type(self): + return _cqltypes[self.__class__.__name__.lower()].apply_parameters([c.cql_type for c in self.types]) + + +class Tuple(BaseCollectionColumn): + """ + Stores a fixed-length set of positional values + + http://docs.datastax.com/en/cql/3.1/cql/cql_reference/tupleType.html + """ + def __init__(self, *args, **kwargs): + """ + :param args: column types representing tuple composition + """ + if not args: + raise ValueError("Tuple must specify at least one inner type") + super(Tuple, self).__init__(args, **kwargs) + self.db_type = 'tuple<{0}>'.format(', '.join(typ.db_type for typ in self.types)) + + def validate(self, value): + val = super(Tuple, self).validate(value) + if val is None: + return + if len(val) > len(self.types): + raise ValidationError("Value %r has more fields than tuple definition (%s)" % + (val, ', '.join(t for t in self.types))) + return tuple(t.validate(v) for t, v in zip(self.types, val)) + + def to_python(self, value): + if value is None: + return tuple() + return tuple(t.to_python(v) for t, v in zip(self.types, value)) + + def to_database(self, value): + if value is None: + return + return tuple(t.to_database(v) for t, v in zip(self.types, value)) + + +class BaseContainerColumn(BaseCollectionColumn): + pass + + +class Set(BaseContainerColumn): + """ + Stores a set of unordered, unique values + + http://www.datastax.com/documentation/cql/3.1/cql/cql_using/use_set_t.html + """ + + _python_type_hashable = False + + def __init__(self, value_type, strict=True, default=set, **kwargs): + """ + :param value_type: a column class indicating the types of the value + :param strict: sets whether non set values will be coerced to set + type on validation, or raise a validation error, defaults to True + """ + self.strict = strict + super(Set, self).__init__((value_type,), default=default, **kwargs) + self.value_col = self.types[0] + if not self.value_col._python_type_hashable: + raise ValidationError("Cannot create a Set with unhashable value type (see PYTHON-494)") + self.db_type = 'set<{0}>'.format(self.value_col.db_type) + + def validate(self, value): + val = super(Set, self).validate(value) + if val is None: + return + types = (set, util.SortedSet) if self.strict else (set, util.SortedSet, list, tuple) + if not isinstance(val, types): + if self.strict: + raise ValidationError('{0} {1} is not a set object'.format(self.column_name, val)) + else: + raise ValidationError('{0} {1} cannot be coerced to a set object'.format(self.column_name, val)) + + if None in val: + raise ValidationError("{0} None not allowed in a set".format(self.column_name)) + # TODO: stop doing this conversion because it doesn't support non-hashable collections as keys (cassandra does) + # will need to start using the cassandra.util types in the next major rev (PYTHON-494) + return set(self.value_col.validate(v) for v in val) + + def to_python(self, value): + if value is None: + return set() + return set(self.value_col.to_python(v) for v in value) + + def to_database(self, value): + if value is None: + return None + return set(self.value_col.to_database(v) for v in value) + + +class List(BaseContainerColumn): + """ + Stores a list of ordered values + + http://www.datastax.com/documentation/cql/3.1/cql/cql_using/use_list_t.html + """ + + _python_type_hashable = False + + def __init__(self, value_type, default=list, **kwargs): + """ + :param value_type: a column class indicating the types of the value + """ + super(List, self).__init__((value_type,), default=default, **kwargs) + self.value_col = self.types[0] + self.db_type = 'list<{0}>'.format(self.value_col.db_type) + + def validate(self, value): + val = super(List, self).validate(value) + if val is None: + return + if not isinstance(val, (set, list, tuple)): + raise ValidationError('{0} {1} is not a list object'.format(self.column_name, val)) + if None in val: + raise ValidationError("{0} None is not allowed in a list".format(self.column_name)) + return [self.value_col.validate(v) for v in val] + + def to_python(self, value): + if value is None: + return [] + return [self.value_col.to_python(v) for v in value] + + def to_database(self, value): + if value is None: + return None + return [self.value_col.to_database(v) for v in value] + + +class Map(BaseContainerColumn): + """ + Stores a key -> value map (dictionary) + + https://docs.datastax.com/en/dse/6.7/cql/cql/cql_using/useMap.html + """ + + _python_type_hashable = False + + def __init__(self, key_type, value_type, default=dict, **kwargs): + """ + :param key_type: a column class indicating the types of the key + :param value_type: a column class indicating the types of the value + """ + super(Map, self).__init__((key_type, value_type), default=default, **kwargs) + self.key_col = self.types[0] + self.value_col = self.types[1] + + if not self.key_col._python_type_hashable: + raise ValidationError("Cannot create a Map with unhashable key type (see PYTHON-494)") + + self.db_type = 'map<{0}, {1}>'.format(self.key_col.db_type, self.value_col.db_type) + + def validate(self, value): + val = super(Map, self).validate(value) + if val is None: + return + if not isinstance(val, (dict, util.OrderedMap)): + raise ValidationError('{0} {1} is not a dict object'.format(self.column_name, val)) + if None in val: + raise ValidationError("{0} None is not allowed in a map".format(self.column_name)) + # TODO: stop doing this conversion because it doesn't support non-hashable collections as keys (cassandra does) + # will need to start using the cassandra.util types in the next major rev (PYTHON-494) + return dict((self.key_col.validate(k), self.value_col.validate(v)) for k, v in val.items()) + + def to_python(self, value): + if value is None: + return {} + if value is not None: + return dict((self.key_col.to_python(k), self.value_col.to_python(v)) for k, v in value.items()) + + def to_database(self, value): + if value is None: + return None + return dict((self.key_col.to_database(k), self.value_col.to_database(v)) for k, v in value.items()) + + +class UDTValueManager(BaseValueManager): + @property + def changed(self): + if self.explicit: + return self.value != self.previous_value + + default_value = self.column.get_default() + if not self.column._val_is_null(default_value): + return self.value != default_value + elif self.previous_value is None: + return not self.column._val_is_null(self.value) and self.value.has_changed_fields() + + return False + + def reset_previous_value(self): + if self.value is not None: + self.value.reset_changed_fields() + self.previous_value = copy(self.value) + + +class UserDefinedType(Column): + """ + User Defined Type column + + http://www.datastax.com/documentation/cql/3.1/cql/cql_using/cqlUseUDT.html + + These columns are represented by a specialization of :class:`cassandra.cqlengine.usertype.UserType`. + + Please see :ref:`user_types` for examples and discussion. + """ + + value_manager = UDTValueManager + + def __init__(self, user_type, **kwargs): + """ + :param type user_type: specifies the :class:`~.cqlengine.usertype.UserType` model of the column + """ + self.user_type = user_type + self.db_type = "frozen<%s>" % user_type.type_name() + super(UserDefinedType, self).__init__(**kwargs) + + @property + def sub_types(self): + return list(self.user_type._fields.values()) + + @property + def cql_type(self): + return UserType.make_udt_class(keyspace='', udt_name=self.user_type.type_name(), + field_names=[c.db_field_name for c in self.user_type._fields.values()], + field_types=[c.cql_type for c in self.user_type._fields.values()]) + + def validate(self, value): + val = super(UserDefinedType, self).validate(value) + if val is None: + return + val.validate() + return val + + def to_python(self, value): + if value is None: + return + + for name, field in self.user_type._fields.items(): + if value[name] is not None or isinstance(field, BaseContainerColumn): + value[name] = field.to_python(value[name]) + + return value + + def to_database(self, value): + if value is None: + return + + copied_value = deepcopy(value) + for name, field in self.user_type._fields.items(): + if copied_value[name] is not None or isinstance(field, BaseContainerColumn): + copied_value[name] = field.to_database(copied_value[name]) + + return copied_value + + +def resolve_udts(col_def, out_list): + for col in col_def.sub_types: + resolve_udts(col, out_list) + if isinstance(col_def, UserDefinedType): + out_list.append(col_def.user_type) + + +class _PartitionKeysToken(Column): + """ + virtual column representing token of partition columns. + Used by filter(pk__token=Token(...)) filters + """ + + def __init__(self, model): + self.partition_columns = list(model._partition_keys.values()) + super(_PartitionKeysToken, self).__init__(partition_key=True) + + @property + def db_field_name(self): + return 'token({0})'.format(', '.join(['"{0}"'.format(c.db_field_name) for c in self.partition_columns])) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/connection.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..bf3e55a2e8dcdebc292d9c84efdab1ab3b494023 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/connection.py @@ -0,0 +1,391 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from collections import defaultdict +import logging +import threading + +from cassandra.cluster import Cluster, _ConfigMode, _NOT_SET, NoHostAvailable, UserTypeDoesNotExist, ConsistencyLevel +from cassandra.query import SimpleStatement, dict_factory + +from cassandra.cqlengine import CQLEngineException +from cassandra.cqlengine.statements import BaseCQLStatement + + +log = logging.getLogger(__name__) + +NOT_SET = _NOT_SET # required for passing timeout to Session.execute + +cluster = None +session = None + +# connections registry +DEFAULT_CONNECTION = object() +_connections = {} + +# Because type models may be registered before a connection is present, +# and because sessions may be replaced, we must register UDTs here, in order +# to have them registered when a new session is established. +udt_by_keyspace = defaultdict(dict) + + +def format_log_context(msg, connection=None, keyspace=None): + """Format log message to add keyspace and connection context""" + connection_info = connection or 'DEFAULT_CONNECTION' + + if keyspace: + msg = '[Connection: {0}, Keyspace: {1}] {2}'.format(connection_info, keyspace, msg) + else: + msg = '[Connection: {0}] {1}'.format(connection_info, msg) + return msg + + +class UndefinedKeyspaceException(CQLEngineException): + pass + + +class Connection(object): + """CQLEngine Connection""" + + name = None + hosts = None + + consistency = None + retry_connect = False + lazy_connect = False + lazy_connect_lock = None + cluster_options = None + + cluster = None + session = None + + def __init__(self, name, hosts, consistency=None, + lazy_connect=False, retry_connect=False, cluster_options=None): + self.hosts = hosts + self.name = name + self.consistency = consistency + self.lazy_connect = lazy_connect + self.retry_connect = retry_connect + self.cluster_options = cluster_options if cluster_options else {} + self.lazy_connect_lock = threading.RLock() + + @classmethod + def from_session(cls, name, session): + instance = cls(name=name, hosts=session.hosts) + instance.cluster, instance.session = session.cluster, session + instance.setup_session() + return instance + + def setup(self): + """Setup the connection""" + global cluster, session + + if 'username' in self.cluster_options or 'password' in self.cluster_options: + raise CQLEngineException("Username & Password are now handled by using the native driver's auth_provider") + + if self.lazy_connect: + return + + if 'cloud' in self.cluster_options: + if self.hosts: + log.warning("Ignoring hosts %s because a cloud config was provided.", self.hosts) + self.cluster = Cluster(**self.cluster_options) + else: + self.cluster = Cluster(self.hosts, **self.cluster_options) + + try: + self.session = self.cluster.connect() + log.debug(format_log_context("connection initialized with internally created session", connection=self.name)) + except NoHostAvailable: + if self.retry_connect: + log.warning(format_log_context("connect failed, setting up for re-attempt on first use", connection=self.name)) + self.lazy_connect = True + raise + + if DEFAULT_CONNECTION in _connections and _connections[DEFAULT_CONNECTION] == self: + cluster = _connections[DEFAULT_CONNECTION].cluster + session = _connections[DEFAULT_CONNECTION].session + + self.setup_session() + + def setup_session(self): + if self.cluster._config_mode == _ConfigMode.PROFILES: + self.cluster.profile_manager.default.row_factory = dict_factory + if self.consistency is not None: + self.cluster.profile_manager.default.consistency_level = self.consistency + else: + self.session.row_factory = dict_factory + if self.consistency is not None: + self.session.default_consistency_level = self.consistency + enc = self.session.encoder + enc.mapping[tuple] = enc.cql_encode_tuple + _register_known_types(self.session.cluster) + + def handle_lazy_connect(self): + + # if lazy_connect is False, it means the cluster is setup and ready + # No need to acquire the lock + if not self.lazy_connect: + return + + with self.lazy_connect_lock: + # lazy_connect might have been set to False by another thread while waiting the lock + # In this case, do nothing. + if self.lazy_connect: + log.debug(format_log_context("Lazy connect enabled", connection=self.name)) + self.lazy_connect = False + self.setup() + + +def register_connection(name, hosts=None, consistency=None, lazy_connect=False, + retry_connect=False, cluster_options=None, default=False, + session=None): + """ + Add a connection to the connection registry. ``hosts`` and ``session`` are + mutually exclusive, and ``consistency``, ``lazy_connect``, + ``retry_connect``, and ``cluster_options`` only work with ``hosts``. Using + ``hosts`` will create a new :class:`cassandra.cluster.Cluster` and + :class:`cassandra.cluster.Session`. + + :param list hosts: list of hosts, (``contact_points`` for :class:`cassandra.cluster.Cluster`). + :param int consistency: The default :class:`~.ConsistencyLevel` for the + registered connection's new session. Default is the same as + :attr:`.Session.default_consistency_level`. For use with ``hosts`` only; + will fail when used with ``session``. + :param bool lazy_connect: True if should not connect until first use. For + use with ``hosts`` only; will fail when used with ``session``. + :param bool retry_connect: True if we should retry to connect even if there + was a connection failure initially. For use with ``hosts`` only; will + fail when used with ``session``. + :param dict cluster_options: A dict of options to be used as keyword + arguments to :class:`cassandra.cluster.Cluster`. For use with ``hosts`` + only; will fail when used with ``session``. + :param bool default: If True, set the new connection as the cqlengine + default + :param Session session: A :class:`cassandra.cluster.Session` to be used in + the created connection. + """ + + if name in _connections: + log.warning("Registering connection '{0}' when it already exists.".format(name)) + + if session is not None: + invalid_config_args = (hosts is not None or + consistency is not None or + lazy_connect is not False or + retry_connect is not False or + cluster_options is not None) + if invalid_config_args: + raise CQLEngineException( + "Session configuration arguments and 'session' argument are mutually exclusive" + ) + conn = Connection.from_session(name, session=session) + else: # use hosts argument + conn = Connection( + name, hosts=hosts, + consistency=consistency, lazy_connect=lazy_connect, + retry_connect=retry_connect, cluster_options=cluster_options + ) + conn.setup() + + _connections[name] = conn + + if default: + set_default_connection(name) + + return conn + + +def unregister_connection(name): + global cluster, session + + if name not in _connections: + return + + if DEFAULT_CONNECTION in _connections and _connections[name] == _connections[DEFAULT_CONNECTION]: + del _connections[DEFAULT_CONNECTION] + cluster = None + session = None + + conn = _connections[name] + if conn.cluster: + conn.cluster.shutdown() + del _connections[name] + log.debug("Connection '{0}' has been removed from the registry.".format(name)) + + +def set_default_connection(name): + global cluster, session + + if name not in _connections: + raise CQLEngineException("Connection '{0}' doesn't exist.".format(name)) + + log.debug("Connection '{0}' has been set as default.".format(name)) + _connections[DEFAULT_CONNECTION] = _connections[name] + cluster = _connections[name].cluster + session = _connections[name].session + + +def get_connection(name=None): + + if not name: + name = DEFAULT_CONNECTION + + if name not in _connections: + raise CQLEngineException("Connection name '{0}' doesn't exist in the registry.".format(name)) + + conn = _connections[name] + conn.handle_lazy_connect() + + return conn + + +def default(): + """ + Configures the default connection to localhost, using the driver defaults + (except for row_factory) + """ + + try: + conn = get_connection() + if conn.session: + log.warning("configuring new default connection for cqlengine when one was already set") + except: + pass + + register_connection('default', hosts=None, default=True) + + log.debug("cqlengine connection initialized with default session to localhost") + + +def set_session(s): + """ + Configures the default connection with a preexisting :class:`cassandra.cluster.Session` + + Note: the mapper presently requires a Session :attr:`cassandra.cluster.Session.row_factory` set to ``dict_factory``. + This may be relaxed in the future + """ + + try: + conn = get_connection() + except CQLEngineException: + # no default connection set; initalize one + register_connection('default', session=s, default=True) + conn = get_connection() + else: + if conn.session: + log.warning("configuring new default session for cqlengine when one was already set") + + if not any([ + s.cluster.profile_manager.default.row_factory is dict_factory and s.cluster._config_mode in [_ConfigMode.PROFILES, _ConfigMode.UNCOMMITTED], + s.row_factory is dict_factory and s.cluster._config_mode in [_ConfigMode.LEGACY, _ConfigMode.UNCOMMITTED], + ]): + raise CQLEngineException("Failed to initialize: row_factory must be 'dict_factory'") + + conn.session = s + conn.cluster = s.cluster + + # Set default keyspace from given session's keyspace + if conn.session.keyspace: + from cassandra.cqlengine import models + models.DEFAULT_KEYSPACE = conn.session.keyspace + + conn.setup_session() + + log.debug("cqlengine default connection initialized with %s", s) + + +# TODO next major: if a cloud config is specified in kwargs, hosts will be ignored. +# This function should be refactored to reflect this change. PYTHON-1265 +def setup( + hosts, + default_keyspace, + consistency=None, + lazy_connect=False, + retry_connect=False, + **kwargs): + """ + Setup the driver connection used by the mapper + + :param list hosts: list of hosts, (``contact_points`` for :class:`cassandra.cluster.Cluster`) + :param str default_keyspace: The default keyspace to use + :param int consistency: The global default :class:`~.ConsistencyLevel` - default is the same as :attr:`.Session.default_consistency_level` + :param bool lazy_connect: True if should not connect until first use + :param bool retry_connect: True if we should retry to connect even if there was a connection failure initially + :param kwargs: Pass-through keyword arguments for :class:`cassandra.cluster.Cluster` + """ + + from cassandra.cqlengine import models + models.DEFAULT_KEYSPACE = default_keyspace + + register_connection('default', hosts=hosts, consistency=consistency, lazy_connect=lazy_connect, + retry_connect=retry_connect, cluster_options=kwargs, default=True) + + +def execute(query, params=None, consistency_level=None, timeout=NOT_SET, connection=None): + + conn = get_connection(connection) + + if not conn.session: + raise CQLEngineException("It is required to setup() cqlengine before executing queries") + + if isinstance(query, SimpleStatement): + pass # + elif isinstance(query, BaseCQLStatement): + params = query.get_context() + query = SimpleStatement(str(query), consistency_level=consistency_level, fetch_size=query.fetch_size) + elif isinstance(query, str): + query = SimpleStatement(query, consistency_level=consistency_level) + log.debug(format_log_context('Query: {}, Params: {}'.format(query.query_string, params), connection=connection)) + + result = conn.session.execute(query, params, timeout=timeout) + + return result + + +def get_session(connection=None): + conn = get_connection(connection) + return conn.session + + +def get_cluster(connection=None): + conn = get_connection(connection) + if not conn.cluster: + raise CQLEngineException("%s.cluster is not configured. Call one of the setup or default functions first." % __name__) + return conn.cluster + + +def register_udt(keyspace, type_name, klass, connection=None): + udt_by_keyspace[keyspace][type_name] = klass + + try: + cluster = get_cluster(connection) + except CQLEngineException: + cluster = None + + if cluster: + try: + cluster.register_user_type(keyspace, type_name, klass) + except UserTypeDoesNotExist: + pass # new types are covered in management sync functions + + +def _register_known_types(cluster): + from cassandra.cqlengine import models + for ks_name, name_type_map in udt_by_keyspace.items(): + for type_name, klass in name_type_map.items(): + try: + cluster.register_user_type(ks_name or models.DEFAULT_KEYSPACE, type_name, klass) + except UserTypeDoesNotExist: + pass # new types are covered in management sync functions diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/functions.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/functions.py new file mode 100644 index 0000000000000000000000000000000000000000..606f5bc330c306632cb3e2fe391a4cac321532d4 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/functions.py @@ -0,0 +1,118 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import datetime + +from cassandra.cqlengine import UnicodeMixin, ValidationError + +def get_total_seconds(td): + return td.total_seconds() + +class QueryValue(UnicodeMixin): + """ + Base class for query filter values. Subclasses of these classes can + be passed into .filter() keyword args + """ + + format_string = '%({0})s' + + def __init__(self, value): + self.value = value + self.context_id = None + + def __unicode__(self): + return self.format_string.format(self.context_id) + + def set_context_id(self, ctx_id): + self.context_id = ctx_id + + def get_context_size(self): + return 1 + + def update_context(self, ctx): + ctx[str(self.context_id)] = self.value + + +class BaseQueryFunction(QueryValue): + """ + Base class for filtering functions. Subclasses of these classes can + be passed into .filter() and will be translated into CQL functions in + the resulting query + """ + pass + + +class TimeUUIDQueryFunction(BaseQueryFunction): + + def __init__(self, value): + """ + :param value: the time to create bounding time uuid from + :type value: datetime + """ + if not isinstance(value, datetime): + raise ValidationError('datetime instance is required') + super(TimeUUIDQueryFunction, self).__init__(value) + + def to_database(self, val): + epoch = datetime(1970, 1, 1, tzinfo=val.tzinfo) + offset = get_total_seconds(epoch.tzinfo.utcoffset(epoch)) if epoch.tzinfo else 0 + return int((get_total_seconds(val - epoch) - offset) * 1000) + + def update_context(self, ctx): + ctx[str(self.context_id)] = self.to_database(self.value) + + +class MinTimeUUID(TimeUUIDQueryFunction): + """ + return a fake timeuuid corresponding to the smallest possible timeuuid for the given timestamp + + http://cassandra.apache.org/doc/cql3/CQL-3.0.html#timeuuidFun + """ + format_string = 'MinTimeUUID(%({0})s)' + + +class MaxTimeUUID(TimeUUIDQueryFunction): + """ + return a fake timeuuid corresponding to the largest possible timeuuid for the given timestamp + + http://cassandra.apache.org/doc/cql3/CQL-3.0.html#timeuuidFun + """ + format_string = 'MaxTimeUUID(%({0})s)' + + +class Token(BaseQueryFunction): + """ + compute the token for a given partition key + + http://cassandra.apache.org/doc/cql3/CQL-3.0.html#tokenFun + """ + def __init__(self, *values): + if len(values) == 1 and isinstance(values[0], (list, tuple)): + values = values[0] + super(Token, self).__init__(values) + self._columns = None + + def set_columns(self, columns): + self._columns = columns + + def get_context_size(self): + return len(self.value) + + def __unicode__(self): + token_args = ', '.join('%({0})s'.format(self.context_id + i) for i in range(self.get_context_size())) + return "token({0})".format(token_args) + + def update_context(self, ctx): + for i, (col, val) in enumerate(zip(self._columns, self.value)): + ctx[str(self.context_id + i)] = col.to_database(val) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/management.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/management.py new file mode 100644 index 0000000000000000000000000000000000000000..4ac4192a80a85bdc3a24c66d5ec5d4a938d707d2 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/management.py @@ -0,0 +1,555 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from collections import namedtuple +import json +import logging +import os +import warnings +from itertools import product + +from cassandra import metadata +from cassandra.cqlengine import CQLEngineException +from cassandra.cqlengine import columns, query +from cassandra.cqlengine.connection import execute, get_cluster, format_log_context +from cassandra.cqlengine.models import Model +from cassandra.cqlengine.named import NamedTable +from cassandra.cqlengine.usertype import UserType + +CQLENG_ALLOW_SCHEMA_MANAGEMENT = 'CQLENG_ALLOW_SCHEMA_MANAGEMENT' + +Field = namedtuple('Field', ['name', 'type']) + +log = logging.getLogger(__name__) + +# system keyspaces +schema_columnfamilies = NamedTable('system', 'schema_columnfamilies') + + +def _get_context(keyspaces, connections): + """Return all the execution contexts""" + + if keyspaces: + if not isinstance(keyspaces, (list, tuple)): + raise ValueError('keyspaces must be a list or a tuple.') + + if connections: + if not isinstance(connections, (list, tuple)): + raise ValueError('connections must be a list or a tuple.') + + keyspaces = keyspaces if keyspaces else [None] + connections = connections if connections else [None] + + return product(connections, keyspaces) + + +def create_keyspace_simple(name, replication_factor, durable_writes=True, connections=None): + """ + Creates a keyspace with SimpleStrategy for replica placement + + If the keyspace already exists, it will not be modified. + + **This function should be used with caution, especially in production environments. + Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).** + + *There are plans to guard schema-modifying functions with an environment-driven conditional.* + + :param str name: name of keyspace to create + :param int replication_factor: keyspace replication factor, used with :attr:`~.SimpleStrategy` + :param bool durable_writes: Write log is bypassed if set to False + :param list connections: List of connection names + """ + _create_keyspace(name, durable_writes, 'SimpleStrategy', + {'replication_factor': replication_factor}, connections=connections) + + +def create_keyspace_network_topology(name, dc_replication_map, durable_writes=True, connections=None): + """ + Creates a keyspace with NetworkTopologyStrategy for replica placement + + If the keyspace already exists, it will not be modified. + + **This function should be used with caution, especially in production environments. + Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).** + + *There are plans to guard schema-modifying functions with an environment-driven conditional.* + + :param str name: name of keyspace to create + :param dict dc_replication_map: map of dc_names: replication_factor + :param bool durable_writes: Write log is bypassed if set to False + :param list connections: List of connection names + """ + _create_keyspace(name, durable_writes, 'NetworkTopologyStrategy', dc_replication_map, connections=connections) + + +def _create_keyspace(name, durable_writes, strategy_class, strategy_options, connections=None): + if not _allow_schema_modification(): + return + + if connections: + if not isinstance(connections, (list, tuple)): + raise ValueError('Connections must be a list or a tuple.') + + def __create_keyspace(name, durable_writes, strategy_class, strategy_options, connection=None): + cluster = get_cluster(connection) + + if name not in cluster.metadata.keyspaces: + log.info(format_log_context("Creating keyspace %s", connection=connection), name) + ks_meta = metadata.KeyspaceMetadata(name, durable_writes, strategy_class, strategy_options) + execute(ks_meta.as_cql_query(), connection=connection) + else: + log.info(format_log_context("Not creating keyspace %s because it already exists", connection=connection), name) + + if connections: + for connection in connections: + __create_keyspace(name, durable_writes, strategy_class, strategy_options, connection=connection) + else: + __create_keyspace(name, durable_writes, strategy_class, strategy_options) + + +def drop_keyspace(name, connections=None): + """ + Drops a keyspace, if it exists. + + *There are plans to guard schema-modifying functions with an environment-driven conditional.* + + **This function should be used with caution, especially in production environments. + Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).** + + :param str name: name of keyspace to drop + :param list connections: List of connection names + """ + if not _allow_schema_modification(): + return + + if connections: + if not isinstance(connections, (list, tuple)): + raise ValueError('Connections must be a list or a tuple.') + + def _drop_keyspace(name, connection=None): + cluster = get_cluster(connection) + if name in cluster.metadata.keyspaces: + execute("DROP KEYSPACE {0}".format(metadata.protect_name(name)), connection=connection) + + if connections: + for connection in connections: + _drop_keyspace(name, connection) + else: + _drop_keyspace(name) + +def _get_index_name_by_column(table, column_name): + """ + Find the index name for a given table and column. + """ + protected_name = metadata.protect_name(column_name) + possible_index_values = [protected_name, "values(%s)" % protected_name] + for index_metadata in table.indexes.values(): + options = dict(index_metadata.index_options) + if options.get('target') in possible_index_values: + return index_metadata.name + + +def sync_table(model, keyspaces=None, connections=None): + """ + Inspects the model and creates / updates the corresponding table and columns. + + If `keyspaces` is specified, the table will be synched for all specified keyspaces. + Note that the `Model.__keyspace__` is ignored in that case. + + If `connections` is specified, the table will be synched for all specified connections. Note that the `Model.__connection__` is ignored in that case. + If not specified, it will try to get the connection from the Model. + + Any User Defined Types used in the table are implicitly synchronized. + + This function can only add fields that are not part of the primary key. + + Note that the attributes removed from the model are not deleted on the database. + They become effectively ignored by (will not show up on) the model. + + **This function should be used with caution, especially in production environments. + Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).** + + *There are plans to guard schema-modifying functions with an environment-driven conditional.* + """ + + context = _get_context(keyspaces, connections) + for connection, keyspace in context: + with query.ContextQuery(model, keyspace=keyspace) as m: + _sync_table(m, connection=connection) + + +def _sync_table(model, connection=None): + if not _allow_schema_modification(): + return + + if not issubclass(model, Model): + raise CQLEngineException("Models must be derived from base Model.") + + if model.__abstract__: + raise CQLEngineException("cannot create table from abstract model") + + cf_name = model.column_family_name() + raw_cf_name = model._raw_column_family_name() + + ks_name = model._get_keyspace() + connection = connection or model._get_connection() + + cluster = get_cluster(connection) + + try: + keyspace = cluster.metadata.keyspaces[ks_name] + except KeyError: + msg = format_log_context("Keyspace '{0}' for model {1} does not exist.", connection=connection) + raise CQLEngineException(msg.format(ks_name, model)) + + tables = keyspace.tables + + syncd_types = set() + for col in model._columns.values(): + udts = [] + columns.resolve_udts(col, udts) + for udt in [u for u in udts if u not in syncd_types]: + _sync_type(ks_name, udt, syncd_types, connection=connection) + + if raw_cf_name not in tables: + log.debug(format_log_context("sync_table creating new table %s", keyspace=ks_name, connection=connection), cf_name) + qs = _get_create_table(model) + + try: + execute(qs, connection=connection) + except CQLEngineException as ex: + # 1.2 doesn't return cf names, so we have to examine the exception + # and ignore if it says the column family already exists + if "Cannot add already existing column family" not in str(ex): + raise + else: + log.debug(format_log_context("sync_table checking existing table %s", keyspace=ks_name, connection=connection), cf_name) + table_meta = tables[raw_cf_name] + + _validate_pk(model, table_meta) + + table_columns = table_meta.columns + model_fields = set() + + for model_name, col in model._columns.items(): + db_name = col.db_field_name + model_fields.add(db_name) + if db_name in table_columns: + col_meta = table_columns[db_name] + if col_meta.cql_type != col.db_type: + msg = format_log_context('Existing table {0} has column "{1}" with a type ({2}) differing from the model type ({3}).' + ' Model should be updated.', keyspace=ks_name, connection=connection) + msg = msg.format(cf_name, db_name, col_meta.cql_type, col.db_type) + warnings.warn(msg) + log.warning(msg) + + continue + + if col.primary_key or col.partition_key: + msg = format_log_context("Cannot add primary key '{0}' (with db_field '{1}') to existing table {2}", keyspace=ks_name, connection=connection) + raise CQLEngineException(msg.format(model_name, db_name, cf_name)) + + query = "ALTER TABLE {0} add {1}".format(cf_name, col.get_column_def()) + execute(query, connection=connection) + + db_fields_not_in_model = model_fields.symmetric_difference(table_columns) + if db_fields_not_in_model: + msg = format_log_context("Table {0} has fields not referenced by model: {1}", keyspace=ks_name, connection=connection) + log.info(msg.format(cf_name, db_fields_not_in_model)) + + _update_options(model, connection=connection) + + table = cluster.metadata.keyspaces[ks_name].tables[raw_cf_name] + + indexes = [c for n, c in model._columns.items() if c.index] + + # TODO: support multiple indexes in C* 3.0+ + for column in indexes: + index_name = _get_index_name_by_column(table, column.db_field_name) + if index_name: + continue + + qs = ['CREATE INDEX'] + qs += ['ON {0}'.format(cf_name)] + qs += ['("{0}")'.format(column.db_field_name)] + qs = ' '.join(qs) + execute(qs, connection=connection) + + +def _validate_pk(model, table_meta): + model_partition = [c.db_field_name for c in model._partition_keys.values()] + meta_partition = [c.name for c in table_meta.partition_key] + model_clustering = [c.db_field_name for c in model._clustering_keys.values()] + meta_clustering = [c.name for c in table_meta.clustering_key] + + if model_partition != meta_partition or model_clustering != meta_clustering: + def _pk_string(partition, clustering): + return "PRIMARY KEY (({0}){1})".format(', '.join(partition), ', ' + ', '.join(clustering) if clustering else '') + raise CQLEngineException("Model {0} PRIMARY KEY composition does not match existing table {1}. " + "Model: {2}; Table: {3}. " + "Update model or drop the table.".format(model, model.column_family_name(), + _pk_string(model_partition, model_clustering), + _pk_string(meta_partition, meta_clustering))) + + +def sync_type(ks_name, type_model, connection=None): + """ + Inspects the type_model and creates / updates the corresponding type. + + Note that the attributes removed from the type_model are not deleted on the database (this operation is not supported). + They become effectively ignored by (will not show up on) the type_model. + + **This function should be used with caution, especially in production environments. + Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).** + + *There are plans to guard schema-modifying functions with an environment-driven conditional.* + """ + if not _allow_schema_modification(): + return + + if not issubclass(type_model, UserType): + raise CQLEngineException("Types must be derived from base UserType.") + + _sync_type(ks_name, type_model, connection=connection) + + +def _sync_type(ks_name, type_model, omit_subtypes=None, connection=None): + + syncd_sub_types = omit_subtypes or set() + for field in type_model._fields.values(): + udts = [] + columns.resolve_udts(field, udts) + for udt in [u for u in udts if u not in syncd_sub_types]: + _sync_type(ks_name, udt, syncd_sub_types, connection=connection) + syncd_sub_types.add(udt) + + type_name = type_model.type_name() + type_name_qualified = "%s.%s" % (ks_name, type_name) + + cluster = get_cluster(connection) + + keyspace = cluster.metadata.keyspaces[ks_name] + defined_types = keyspace.user_types + + if type_name not in defined_types: + log.debug(format_log_context("sync_type creating new type %s", keyspace=ks_name, connection=connection), type_name_qualified) + cql = get_create_type(type_model, ks_name) + execute(cql, connection=connection) + cluster.refresh_user_type_metadata(ks_name, type_name) + type_model.register_for_keyspace(ks_name, connection=connection) + else: + type_meta = defined_types[type_name] + defined_fields = type_meta.field_names + model_fields = set() + for field in type_model._fields.values(): + model_fields.add(field.db_field_name) + if field.db_field_name not in defined_fields: + execute("ALTER TYPE {0} ADD {1}".format(type_name_qualified, field.get_column_def()), connection=connection) + else: + field_type = type_meta.field_types[defined_fields.index(field.db_field_name)] + if field_type != field.db_type: + msg = format_log_context('Existing user type {0} has field "{1}" with a type ({2}) differing from the model user type ({3}).' + ' UserType should be updated.', keyspace=ks_name, connection=connection) + msg = msg.format(type_name_qualified, field.db_field_name, field_type, field.db_type) + warnings.warn(msg) + log.warning(msg) + + type_model.register_for_keyspace(ks_name, connection=connection) + + if len(defined_fields) == len(model_fields): + log.info(format_log_context("Type %s did not require synchronization", keyspace=ks_name, connection=connection), type_name_qualified) + return + + db_fields_not_in_model = model_fields.symmetric_difference(defined_fields) + if db_fields_not_in_model: + msg = format_log_context("Type %s has fields not referenced by model: %s", keyspace=ks_name, connection=connection) + log.info(msg, type_name_qualified, db_fields_not_in_model) + + +def get_create_type(type_model, keyspace): + type_meta = metadata.UserType(keyspace, + type_model.type_name(), + (f.db_field_name for f in type_model._fields.values()), + (v.db_type for v in type_model._fields.values())) + return type_meta.as_cql_query() + + +def _get_create_table(model): + ks_table_name = model.column_family_name() + query_strings = ['CREATE TABLE {0}'.format(ks_table_name)] + + # add column types + pkeys = [] # primary keys + ckeys = [] # clustering keys + qtypes = [] # field types + + def add_column(col): + s = col.get_column_def() + if col.primary_key: + keys = (pkeys if col.partition_key else ckeys) + keys.append('"{0}"'.format(col.db_field_name)) + qtypes.append(s) + + for name, col in model._columns.items(): + add_column(col) + + qtypes.append('PRIMARY KEY (({0}){1})'.format(', '.join(pkeys), ckeys and ', ' + ', '.join(ckeys) or '')) + + query_strings += ['({0})'.format(', '.join(qtypes))] + + property_strings = [] + + _order = ['"{0}" {1}'.format(c.db_field_name, c.clustering_order or 'ASC') for c in model._clustering_keys.values()] + if _order: + property_strings.append('CLUSTERING ORDER BY ({0})'.format(', '.join(_order))) + + # options strings use the V3 format, which matches CQL more closely and does not require mapping + property_strings += metadata.TableMetadataV3._make_option_strings(model.__options__ or {}) + + if property_strings: + query_strings += ['WITH {0}'.format(' AND '.join(property_strings))] + + return ' '.join(query_strings) + + +def _get_table_metadata(model, connection=None): + # returns the table as provided by the native driver for a given model + cluster = get_cluster(connection) + ks = model._get_keyspace() + table = model._raw_column_family_name() + table = cluster.metadata.keyspaces[ks].tables[table] + return table + + +def _options_map_from_strings(option_strings): + # converts options strings to a mapping to strings or dict + options = {} + for option in option_strings: + name, value = option.split('=') + i = value.find('{') + if i >= 0: + value = value[i:value.rfind('}') + 1].replace("'", '"') # from cql single quotes to json double; not aware of any values that would be escaped right now + value = json.loads(value) + else: + value = value.strip() + options[name.strip()] = value + return options + + +def _update_options(model, connection=None): + """Updates the table options for the given model if necessary. + + :param model: The model to update. + :param connection: Name of the connection to use + + :return: `True`, if the options were modified in Cassandra, + `False` otherwise. + :rtype: bool + """ + ks_name = model._get_keyspace() + msg = format_log_context("Checking %s for option differences", keyspace=ks_name, connection=connection) + log.debug(msg, model) + model_options = model.__options__ or {} + + table_meta = _get_table_metadata(model, connection=connection) + # go to CQL string first to normalize meta from different versions + existing_option_strings = set(table_meta._make_option_strings(table_meta.options)) + existing_options = _options_map_from_strings(existing_option_strings) + model_option_strings = metadata.TableMetadataV3._make_option_strings(model_options) + model_options = _options_map_from_strings(model_option_strings) + + update_options = {} + for name, value in model_options.items(): + try: + existing_value = existing_options[name] + except KeyError: + msg = format_log_context("Invalid table option: '%s'; known options: %s", keyspace=ks_name, connection=connection) + raise KeyError(msg % (name, existing_options.keys())) + if isinstance(existing_value, str): + if value != existing_value: + update_options[name] = value + else: + try: + for k, v in value.items(): + # When creating table with compaction 'class': 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy' in Scylla, + # it will be silently changed to 'class': 'LeveledCompactionStrategy' - same for at least SizeTieredCompactionStrategy, + # probably others too. We need to handle this case here. + if k == 'class' and name == 'compaction': + if existing_value[k] != v and existing_value[k] != v.split('.')[-1]: + update_options[name] = value + break + else: + if existing_value[k] != v: + update_options[name] = value + break + except KeyError: + update_options[name] = value + + if update_options: + options = ' AND '.join(metadata.TableMetadataV3._make_option_strings(update_options)) + query = "ALTER TABLE {0} WITH {1}".format(model.column_family_name(), options) + execute(query, connection=connection) + return True + + return False + + +def drop_table(model, keyspaces=None, connections=None): + """ + Drops the table indicated by the model, if it exists. + + If `keyspaces` is specified, the table will be dropped for all specified keyspaces. Note that the `Model.__keyspace__` is ignored in that case. + + If `connections` is specified, the table will be synched for all specified connections. Note that the `Model.__connection__` is ignored in that case. + If not specified, it will try to get the connection from the Model. + + + **This function should be used with caution, especially in production environments. + Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).** + + *There are plans to guard schema-modifying functions with an environment-driven conditional.* + """ + + context = _get_context(keyspaces, connections) + for connection, keyspace in context: + with query.ContextQuery(model, keyspace=keyspace) as m: + _drop_table(m, connection=connection) + + +def _drop_table(model, connection=None): + if not _allow_schema_modification(): + return + + connection = connection or model._get_connection() + + # don't try to delete non existant tables + meta = get_cluster(connection).metadata + + ks_name = model._get_keyspace() + raw_cf_name = model._raw_column_family_name() + + try: + meta.keyspaces[ks_name].tables[raw_cf_name] + execute('DROP TABLE {0};'.format(model.column_family_name()), connection=connection) + except KeyError: + pass + + +def _allow_schema_modification(): + if not os.getenv(CQLENG_ALLOW_SCHEMA_MANAGEMENT): + msg = CQLENG_ALLOW_SCHEMA_MANAGEMENT + " environment variable is not set. Future versions of this package will require this variable to enable management functions." + warnings.warn(msg) + log.warning(msg) + + return True diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/models.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/models.py new file mode 100644 index 0000000000000000000000000000000000000000..bc000016668998c757ed7833729e00039db67b0c --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/models.py @@ -0,0 +1,1086 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +import re +from warnings import warn + +from cassandra.cqlengine import CQLEngineException, ValidationError +from cassandra.cqlengine import columns +from cassandra.cqlengine import connection +from cassandra.cqlengine import query +from cassandra.cqlengine.query import DoesNotExist as _DoesNotExist +from cassandra.cqlengine.query import MultipleObjectsReturned as _MultipleObjectsReturned +from cassandra.metadata import protect_name +from cassandra.util import OrderedDict + +log = logging.getLogger(__name__) + + +def _clone_model_class(model, attrs): + new_type = type(model.__name__, (model,), attrs) + try: + new_type.__abstract__ = model.__abstract__ + new_type.__discriminator_value__ = model.__discriminator_value__ + new_type.__default_ttl__ = model.__default_ttl__ + except AttributeError: + pass + return new_type + + +class ModelException(CQLEngineException): + pass + + +class ModelDefinitionException(ModelException): + pass + + +class PolymorphicModelException(ModelException): + pass + + +class UndefinedKeyspaceWarning(Warning): + pass + +DEFAULT_KEYSPACE = None + + +class hybrid_classmethod(object): + """ + Allows a method to behave as both a class method and + normal instance method depending on how it's called + """ + def __init__(self, clsmethod, instmethod): + self.clsmethod = clsmethod + self.instmethod = instmethod + + def __get__(self, instance, owner): + if instance is None: + return self.clsmethod.__get__(owner, owner) + else: + return self.instmethod.__get__(instance, owner) + + def __call__(self, *args, **kwargs): + """ + Just a hint to IDEs that it's ok to call this + """ + raise NotImplementedError + + +class QuerySetDescriptor(object): + """ + returns a fresh queryset for the given model + it's declared on everytime it's accessed + """ + + def __get__(self, obj, model): + """ :rtype: ModelQuerySet """ + if model.__abstract__: + raise CQLEngineException('cannot execute queries against abstract models') + queryset = model.__queryset__(model) + + # if this is a concrete polymorphic model, and the discriminator + # key is an indexed column, add a filter clause to only return + # logical rows of the proper type + if model._is_polymorphic and not model._is_polymorphic_base: + name, column = model._discriminator_column_name, model._discriminator_column + if column.partition_key or column.index: + # look for existing poly types + return queryset.filter(**{name: model.__discriminator_value__}) + + return queryset + + def __call__(self, *args, **kwargs): + """ + Just a hint to IDEs that it's ok to call this + + :rtype: ModelQuerySet + """ + raise NotImplementedError + + +class ConditionalDescriptor(object): + """ + returns a query set descriptor + """ + def __get__(self, instance, model): + if instance: + def conditional_setter(*prepared_conditional, **unprepared_conditionals): + if len(prepared_conditional) > 0: + conditionals = prepared_conditional[0] + else: + conditionals = instance.objects.iff(**unprepared_conditionals)._conditional + instance._conditional = conditionals + return instance + + return conditional_setter + qs = model.__queryset__(model) + + def conditional_setter(**unprepared_conditionals): + conditionals = model.objects.iff(**unprepared_conditionals)._conditional + qs._conditional = conditionals + return qs + return conditional_setter + + def __call__(self, *args, **kwargs): + raise NotImplementedError + + +class TTLDescriptor(object): + """ + returns a query set descriptor + """ + def __get__(self, instance, model): + if instance: + # instance = copy.deepcopy(instance) + # instance method + def ttl_setter(ts): + instance._ttl = ts + return instance + return ttl_setter + + qs = model.__queryset__(model) + + def ttl_setter(ts): + qs._ttl = ts + return qs + + return ttl_setter + + def __call__(self, *args, **kwargs): + raise NotImplementedError + + +class TimestampDescriptor(object): + """ + returns a query set descriptor with a timestamp specified + """ + def __get__(self, instance, model): + if instance: + # instance method + def timestamp_setter(ts): + instance._timestamp = ts + return instance + return timestamp_setter + + return model.objects.timestamp + + def __call__(self, *args, **kwargs): + raise NotImplementedError + + +class IfNotExistsDescriptor(object): + """ + return a query set descriptor with a if_not_exists flag specified + """ + def __get__(self, instance, model): + if instance: + # instance method + def ifnotexists_setter(ife=True): + instance._if_not_exists = ife + return instance + return ifnotexists_setter + + return model.objects.if_not_exists + + def __call__(self, *args, **kwargs): + raise NotImplementedError + + +class IfExistsDescriptor(object): + """ + return a query set descriptor with a if_exists flag specified + """ + def __get__(self, instance, model): + if instance: + # instance method + def ifexists_setter(ife=True): + instance._if_exists = ife + return instance + return ifexists_setter + + return model.objects.if_exists + + def __call__(self, *args, **kwargs): + raise NotImplementedError + + +class ConsistencyDescriptor(object): + """ + returns a query set descriptor if called on Class, instance if it was an instance call + """ + def __get__(self, instance, model): + if instance: + # instance = copy.deepcopy(instance) + def consistency_setter(consistency): + instance.__consistency__ = consistency + return instance + return consistency_setter + + qs = model.__queryset__(model) + + def consistency_setter(consistency): + qs._consistency = consistency + return qs + + return consistency_setter + + def __call__(self, *args, **kwargs): + raise NotImplementedError + + +class UsingDescriptor(object): + """ + return a query set descriptor with a connection context specified + """ + def __get__(self, instance, model): + if instance: + # instance method + def using_setter(connection=None): + if connection: + instance._connection = connection + return instance + return using_setter + + return model.objects.using + + def __call__(self, *args, **kwargs): + raise NotImplementedError + + +class ColumnQueryEvaluator(query.AbstractQueryableColumn): + """ + Wraps a column and allows it to be used in comparator + expressions, returning query operators + + ie: + Model.column == 5 + """ + + def __init__(self, column): + self.column = column + + def __unicode__(self): + return self.column.db_field_name + + def _get_column(self): + return self.column + + +class ColumnDescriptor(object): + """ + Handles the reading and writing of column values to and from + a model instance's value manager, as well as creating + comparator queries + """ + + def __init__(self, column): + """ + :param column: + :type column: columns.Column + :return: + """ + self.column = column + self.query_evaluator = ColumnQueryEvaluator(self.column) + + def __get__(self, instance, owner): + """ + Returns either the value or column, depending + on if an instance is provided or not + + :param instance: the model instance + :type instance: Model + """ + try: + return instance._values[self.column.column_name].getval() + except AttributeError: + return self.query_evaluator + + def __set__(self, instance, value): + """ + Sets the value on an instance, raises an exception with classes + TODO: use None instance to create update statements + """ + if instance: + return instance._values[self.column.column_name].setval(value) + else: + raise AttributeError('cannot reassign column values') + + def __delete__(self, instance): + """ + Sets the column value to None, if possible + """ + if instance: + if self.column.can_delete: + instance._values[self.column.column_name].delval() + else: + raise AttributeError('cannot delete {0} columns'.format(self.column.column_name)) + + +class BaseModel(object): + """ + The base model class, don't inherit from this, inherit from Model, defined below + """ + + class DoesNotExist(_DoesNotExist): + pass + + class MultipleObjectsReturned(_MultipleObjectsReturned): + pass + + objects = QuerySetDescriptor() + ttl = TTLDescriptor() + consistency = ConsistencyDescriptor() + iff = ConditionalDescriptor() + + # custom timestamps, see USING TIMESTAMP X + timestamp = TimestampDescriptor() + + if_not_exists = IfNotExistsDescriptor() + + if_exists = IfExistsDescriptor() + + using = UsingDescriptor() + + # _len is lazily created by __len__ + + __table_name__ = None + + __table_name_case_sensitive__ = False + + __keyspace__ = None + + __connection__ = None + + __discriminator_value__ = None + + __options__ = None + + __compute_routing_key__ = True + + # the queryset class used for this class + __queryset__ = query.ModelQuerySet + __dmlquery__ = query.DMLQuery + + __consistency__ = None # can be set per query + + _timestamp = None # optional timestamp to include with the operation (USING TIMESTAMP) + + _if_not_exists = False # optional if_not_exists flag to check existence before insertion + + _if_exists = False # optional if_exists flag to check existence before update + + _table_name = None # used internally to cache a derived table name + + _connection = None + + def __init__(self, **values): + self._ttl = None + self._timestamp = None + self._conditional = None + self._batch = None + self._timeout = connection.NOT_SET + self._is_persisted = False + self._connection = None + + self._values = {} + for name, column in self._columns.items(): + # Set default values on instantiation. Thanks to this, we don't have + # to wait anylonger for a call to validate() to have CQLengine set + # default columns values. + column_default = column.get_default() if column.has_default else None + value = values.get(name, column_default) + if value is not None or isinstance(column, columns.BaseContainerColumn): + value = column.to_python(value) + value_mngr = column.value_manager(self, column, value) + value_mngr.explicit = name in values + self._values[name] = value_mngr + + def __repr__(self): + return '{0}({1})'.format(self.__class__.__name__, + ', '.join('{0}={1!r}'.format(k, getattr(self, k)) + for k in self._defined_columns.keys() + if k != self._discriminator_column_name)) + + def __str__(self): + """ + Pretty printing of models by their primary key + """ + return '{0} <{1}>'.format(self.__class__.__name__, + ', '.join('{0}={1}'.format(k, getattr(self, k)) for k in self._primary_keys.keys())) + + @classmethod + def _routing_key_from_values(cls, pk_values, protocol_version): + return cls._key_serializer(pk_values, protocol_version) + + @classmethod + def _discover_polymorphic_submodels(cls): + if not cls._is_polymorphic_base: + raise ModelException('_discover_polymorphic_submodels can only be called on polymorphic base classes') + + def _discover(klass): + if not klass._is_polymorphic_base and klass.__discriminator_value__ is not None: + cls._discriminator_map[klass.__discriminator_value__] = klass + for subklass in klass.__subclasses__(): + _discover(subklass) + _discover(cls) + + @classmethod + def _get_model_by_discriminator_value(cls, key): + if not cls._is_polymorphic_base: + raise ModelException('_get_model_by_discriminator_value can only be called on polymorphic base classes') + return cls._discriminator_map.get(key) + + @classmethod + def _construct_instance(cls, values): + """ + method used to construct instances from query results + this is where polymorphic deserialization occurs + """ + # we're going to take the values, which is from the DB as a dict + # and translate that into our local fields + # the db_map is a db_field -> model field map + if cls._db_map: + values = dict((cls._db_map.get(k, k), v) for k, v in values.items()) + + if cls._is_polymorphic: + disc_key = values.get(cls._discriminator_column_name) + + if disc_key is None: + raise PolymorphicModelException('discriminator value was not found in values') + + poly_base = cls if cls._is_polymorphic_base else cls._polymorphic_base + + klass = poly_base._get_model_by_discriminator_value(disc_key) + if klass is None: + poly_base._discover_polymorphic_submodels() + klass = poly_base._get_model_by_discriminator_value(disc_key) + if klass is None: + raise PolymorphicModelException( + 'unrecognized discriminator column {0} for class {1}'.format(disc_key, poly_base.__name__) + ) + + if not issubclass(klass, cls): + raise PolymorphicModelException( + '{0} is not a subclass of {1}'.format(klass.__name__, cls.__name__) + ) + + values = dict((k, v) for k, v in values.items() if k in klass._columns.keys()) + + else: + klass = cls + + instance = klass(**values) + instance._set_persisted(force=True) + return instance + + def _set_persisted(self, force=False): + # ensure we don't modify to any values not affected by the last save/update + for v in [v for v in self._values.values() if v.changed or force]: + v.reset_previous_value() + v.explicit = False + self._is_persisted = True + + def _can_update(self): + """ + Called by the save function to check if this should be + persisted with update or insert + + :return: + """ + if not self._is_persisted: + return False + + return all([not self._values[k].changed for k in self._primary_keys]) + + @classmethod + def _get_keyspace(cls): + """ + Returns the manual keyspace, if set, otherwise the default keyspace + """ + return cls.__keyspace__ or DEFAULT_KEYSPACE + + @classmethod + def _get_column(cls, name): + """ + Returns the column matching the given name, raising a key error if + it doesn't exist + + :param name: the name of the column to return + :rtype: Column + """ + return cls._columns[name] + + @classmethod + def _get_column_by_db_name(cls, name): + """ + Returns the column, mapped by db_field name + """ + return cls._columns.get(cls._db_map.get(name, name)) + + def __eq__(self, other): + if self.__class__ != other.__class__: + return False + + # check attribute keys + keys = set(self._columns.keys()) + other_keys = set(other._columns.keys()) + if keys != other_keys: + return False + + return all(getattr(self, key, None) == getattr(other, key, None) for key in other_keys) + + def __ne__(self, other): + return not self.__eq__(other) + + @classmethod + def column_family_name(cls, include_keyspace=True): + """ + Returns the column family name if it's been defined + otherwise, it creates it from the module and class name + """ + cf_name = protect_name(cls._raw_column_family_name()) + if include_keyspace: + keyspace = cls._get_keyspace() + if not keyspace: + raise CQLEngineException("Model keyspace is not set and no default is available. Set model keyspace or setup connection before attempting to generate a query.") + return '{0}.{1}'.format(protect_name(keyspace), cf_name) + + return cf_name + + + @classmethod + def _raw_column_family_name(cls): + if not cls._table_name: + if cls.__table_name__: + if cls.__table_name_case_sensitive__: + warn("Model __table_name_case_sensitive__ will be removed in 4.0.", PendingDeprecationWarning) + cls._table_name = cls.__table_name__ + else: + table_name = cls.__table_name__.lower() + if cls.__table_name__ != table_name: + warn(("Model __table_name__ will be case sensitive by default in 4.0. " + "You should fix the __table_name__ value of the '{0}' model.").format(cls.__name__)) + cls._table_name = table_name + else: + if cls._is_polymorphic and not cls._is_polymorphic_base: + cls._table_name = cls._polymorphic_base._raw_column_family_name() + else: + camelcase = re.compile(r'([a-z])([A-Z])') + ccase = lambda s: camelcase.sub(lambda v: '{0}_{1}'.format(v.group(1), v.group(2).lower()), s) + + cf_name = ccase(cls.__name__) + # trim to less than 48 characters or cassandra will complain + cf_name = cf_name[-48:] + cf_name = cf_name.lower() + cf_name = re.sub(r'^_+', '', cf_name) + cls._table_name = cf_name + + return cls._table_name + + def _set_column_value(self, name, value): + """Function to change a column value without changing the value manager states""" + self._values[name].value = value # internal assignement, skip the main setter + + def validate(self): + """ + Cleans and validates the field values + """ + for name, col in self._columns.items(): + v = getattr(self, name) + if v is None and not self._values[name].explicit and col.has_default: + v = col.get_default() + val = col.validate(v) + self._set_column_value(name, val) + + # Let an instance be used like a dict of its columns keys/values + def __iter__(self): + """ Iterate over column ids. """ + for column_id in self._columns.keys(): + yield column_id + + def __getitem__(self, key): + """ Returns column's value. """ + if not isinstance(key, str): + raise TypeError + if key not in self._columns.keys(): + raise KeyError + return getattr(self, key) + + def __setitem__(self, key, val): + """ Sets a column's value. """ + if not isinstance(key, str): + raise TypeError + if key not in self._columns.keys(): + raise KeyError + return setattr(self, key, val) + + def __len__(self): + """ + Returns the number of columns defined on that model. + """ + try: + return self._len + except: + self._len = len(self._columns.keys()) + return self._len + + def keys(self): + """ Returns a list of column IDs. """ + return [k for k in self] + + def values(self): + """ Returns list of column values. """ + return [self[k] for k in self] + + def items(self): + """ Returns a list of column ID/value tuples. """ + return [(k, self[k]) for k in self] + + def _as_dict(self): + """ Returns a map of column names to cleaned values """ + values = self._dynamic_columns or {} + for name, col in self._columns.items(): + values[name] = col.to_database(getattr(self, name, None)) + return values + + @classmethod + def create(cls, **kwargs): + """ + Create an instance of this model in the database. + + Takes the model column values as keyword arguments. Setting a value to + `None` is equivalent to running a CQL `DELETE` on that column. + + Returns the instance. + """ + extra_columns = set(kwargs.keys()) - set(cls._columns.keys()) + if extra_columns: + raise ValidationError("Incorrect columns passed: {0}".format(extra_columns)) + return cls.objects.create(**kwargs) + + @classmethod + def all(cls): + """ + Returns a queryset representing all stored objects + + This is a pass-through to the model objects().all() + """ + return cls.objects.all() + + @classmethod + def filter(cls, *args, **kwargs): + """ + Returns a queryset based on filter parameters. + + This is a pass-through to the model objects().:method:`~cqlengine.queries.filter`. + """ + return cls.objects.filter(*args, **kwargs) + + @classmethod + def get(cls, *args, **kwargs): + """ + Returns a single object based on the passed filter constraints. + + This is a pass-through to the model objects().:method:`~cqlengine.queries.get`. + """ + return cls.objects.get(*args, **kwargs) + + def timeout(self, timeout): + """ + Sets a timeout for use in :meth:`~.save`, :meth:`~.update`, and :meth:`~.delete` + operations + """ + assert self._batch is None, 'Setting both timeout and batch is not supported' + self._timeout = timeout + return self + + def save(self): + """ + Saves an object to the database. + + .. code-block:: python + + #create a person instance + person = Person(first_name='Kimberly', last_name='Eggleston') + #saves it to Cassandra + person.save() + """ + + # handle polymorphic models + if self._is_polymorphic: + if self._is_polymorphic_base: + raise PolymorphicModelException('cannot save polymorphic base model') + else: + setattr(self, self._discriminator_column_name, self.__discriminator_value__) + + self.validate() + self.__dmlquery__(self.__class__, self, + batch=self._batch, + ttl=self._ttl, + timestamp=self._timestamp, + consistency=self.__consistency__, + if_not_exists=self._if_not_exists, + conditional=self._conditional, + timeout=self._timeout, + if_exists=self._if_exists).save() + + self._set_persisted() + + self._timestamp = None + + return self + + def update(self, **values): + """ + Performs an update on the model instance. You can pass in values to set on the model + for updating, or you can call without values to execute an update against any modified + fields. If no fields on the model have been modified since loading, no query will be + performed. Model validation is performed normally. Setting a value to `None` is + equivalent to running a CQL `DELETE` on that column. + + It is possible to do a blind update, that is, to update a field without having first selected the object out of the database. + See :ref:`Blind Updates ` + """ + for column_id, v in values.items(): + col = self._columns.get(column_id) + + # check for nonexistant columns + if col is None: + raise ValidationError( + "{0}.{1} has no column named: {2}".format( + self.__module__, self.__class__.__name__, column_id)) + + # check for primary key update attempts + if col.is_primary_key: + current_value = getattr(self, column_id) + if v != current_value: + raise ValidationError( + "Cannot apply update to primary key '{0}' for {1}.{2}".format( + column_id, self.__module__, self.__class__.__name__)) + + setattr(self, column_id, v) + + # handle polymorphic models + if self._is_polymorphic: + if self._is_polymorphic_base: + raise PolymorphicModelException('cannot update polymorphic base model') + else: + setattr(self, self._discriminator_column_name, self.__discriminator_value__) + + self.validate() + self.__dmlquery__(self.__class__, self, + batch=self._batch, + ttl=self._ttl, + timestamp=self._timestamp, + consistency=self.__consistency__, + conditional=self._conditional, + timeout=self._timeout, + if_exists=self._if_exists).update() + + self._set_persisted() + + self._timestamp = None + + return self + + def delete(self): + """ + Deletes the object from the database + """ + self.__dmlquery__(self.__class__, self, + batch=self._batch, + timestamp=self._timestamp, + consistency=self.__consistency__, + timeout=self._timeout, + conditional=self._conditional, + if_exists=self._if_exists).delete() + + def get_changed_columns(self): + """ + Returns a list of the columns that have been updated since instantiation or save + """ + return [k for k, v in self._values.items() if v.changed] + + @classmethod + def _class_batch(cls, batch): + return cls.objects.batch(batch) + + def _inst_batch(self, batch): + assert self._timeout is connection.NOT_SET, 'Setting both timeout and batch is not supported' + if self._connection: + raise CQLEngineException("Cannot specify a connection on model in batch mode.") + self._batch = batch + return self + + batch = hybrid_classmethod(_class_batch, _inst_batch) + + @classmethod + def _class_get_connection(cls): + return cls.__connection__ + + def _inst_get_connection(self): + return self._connection or self.__connection__ + + _get_connection = hybrid_classmethod(_class_get_connection, _inst_get_connection) + + +class ModelMetaClass(type): + + def __new__(cls, name, bases, attrs): + # move column definitions into columns dict + # and set default column names + column_dict = OrderedDict() + primary_keys = OrderedDict() + pk_name = None + + # get inherited properties + inherited_columns = OrderedDict() + for base in bases: + for k, v in getattr(base, '_defined_columns', {}).items(): + inherited_columns.setdefault(k, v) + + # short circuit __abstract__ inheritance + is_abstract = attrs['__abstract__'] = attrs.get('__abstract__', False) + + # short circuit __discriminator_value__ inheritance + attrs['__discriminator_value__'] = attrs.get('__discriminator_value__') + + # TODO __default__ttl__ should be removed in the next major release + options = attrs.get('__options__') or {} + attrs['__default_ttl__'] = options.get('default_time_to_live') + + column_definitions = [(k, v) for k, v in attrs.items() if isinstance(v, columns.Column)] + column_definitions = sorted(column_definitions, key=lambda x: x[1].position) + + is_polymorphic_base = any([c[1].discriminator_column for c in column_definitions]) + + column_definitions = [x for x in inherited_columns.items()] + column_definitions + discriminator_columns = [c for c in column_definitions if c[1].discriminator_column] + is_polymorphic = len(discriminator_columns) > 0 + if len(discriminator_columns) > 1: + raise ModelDefinitionException('only one discriminator_column can be defined in a model, {0} found'.format(len(discriminator_columns))) + + if attrs['__discriminator_value__'] and not is_polymorphic: + raise ModelDefinitionException('__discriminator_value__ specified, but no base columns defined with discriminator_column=True') + + discriminator_column_name, discriminator_column = discriminator_columns[0] if discriminator_columns else (None, None) + + if isinstance(discriminator_column, (columns.BaseContainerColumn, columns.Counter)): + raise ModelDefinitionException('counter and container columns cannot be used as discriminator columns') + + # find polymorphic base class + polymorphic_base = None + if is_polymorphic and not is_polymorphic_base: + def _get_polymorphic_base(bases): + for base in bases: + if getattr(base, '_is_polymorphic_base', False): + return base + klass = _get_polymorphic_base(base.__bases__) + if klass: + return klass + polymorphic_base = _get_polymorphic_base(bases) + + defined_columns = OrderedDict(column_definitions) + + # check for primary key + if not is_abstract and not any([v.primary_key for k, v in column_definitions]): + raise ModelDefinitionException("At least 1 primary key is required.") + + counter_columns = [c for c in defined_columns.values() if isinstance(c, columns.Counter)] + data_columns = [c for c in defined_columns.values() if not c.primary_key and not isinstance(c, columns.Counter)] + if counter_columns and data_columns: + raise ModelDefinitionException('counter models may not have data columns') + + has_partition_keys = any(v.partition_key for (k, v) in column_definitions) + + def _transform_column(col_name, col_obj): + column_dict[col_name] = col_obj + if col_obj.primary_key: + primary_keys[col_name] = col_obj + col_obj.set_column_name(col_name) + # set properties + attrs[col_name] = ColumnDescriptor(col_obj) + + partition_key_index = 0 + # transform column definitions + for k, v in column_definitions: + # don't allow a column with the same name as a built-in attribute or method + if k in BaseModel.__dict__: + raise ModelDefinitionException("column '{0}' conflicts with built-in attribute/method".format(k)) + + # counter column primary keys are not allowed + if (v.primary_key or v.partition_key) and isinstance(v, columns.Counter): + raise ModelDefinitionException('counter columns cannot be used as primary keys') + + # this will mark the first primary key column as a partition + # key, if one hasn't been set already + if not has_partition_keys and v.primary_key: + v.partition_key = True + has_partition_keys = True + if v.partition_key: + v._partition_key_index = partition_key_index + partition_key_index += 1 + + overriding = column_dict.get(k) + if overriding: + v.position = overriding.position + v.partition_key = overriding.partition_key + v._partition_key_index = overriding._partition_key_index + _transform_column(k, v) + + partition_keys = OrderedDict(k for k in primary_keys.items() if k[1].partition_key) + clustering_keys = OrderedDict(k for k in primary_keys.items() if not k[1].partition_key) + + if attrs.get('__compute_routing_key__', True): + key_cols = [c for c in partition_keys.values()] + partition_key_index = dict((col.db_field_name, col._partition_key_index) for col in key_cols) + key_cql_types = [c.cql_type for c in key_cols] + key_serializer = staticmethod(lambda parts, proto_version: [t.to_binary(p, proto_version) for t, p in zip(key_cql_types, parts)]) + else: + partition_key_index = {} + key_serializer = staticmethod(lambda parts, proto_version: None) + + # setup partition key shortcut + if len(partition_keys) == 0: + if not is_abstract: + raise ModelException("at least one partition key must be defined") + if len(partition_keys) == 1: + pk_name = [x for x in partition_keys.keys()][0] + attrs['pk'] = attrs[pk_name] + else: + # composite partition key case, get/set a tuple of values + _get = lambda self: tuple(self._values[c].getval() for c in partition_keys.keys()) + _set = lambda self, val: tuple(self._values[c].setval(v) for (c, v) in zip(partition_keys.keys(), val)) + attrs['pk'] = property(_get, _set) + + # some validation + col_names = set() + for v in column_dict.values(): + # check for duplicate column names + if v.db_field_name in col_names: + raise ModelException("{0} defines the column '{1}' more than once".format(name, v.db_field_name)) + if v.clustering_order and not (v.primary_key and not v.partition_key): + raise ModelException("clustering_order may be specified only for clustering primary keys") + if v.clustering_order and v.clustering_order.lower() not in ('asc', 'desc'): + raise ModelException("invalid clustering order '{0}' for column '{1}'".format(repr(v.clustering_order), v.db_field_name)) + col_names.add(v.db_field_name) + + # create db_name -> model name map for loading + db_map = {} + for col_name, field in column_dict.items(): + db_field = field.db_field_name + if db_field != col_name: + db_map[db_field] = col_name + + # add management members to the class + attrs['_columns'] = column_dict + attrs['_primary_keys'] = primary_keys + attrs['_defined_columns'] = defined_columns + + # maps the database field to the models key + attrs['_db_map'] = db_map + attrs['_pk_name'] = pk_name + attrs['_dynamic_columns'] = {} + + attrs['_partition_keys'] = partition_keys + attrs['_partition_key_index'] = partition_key_index + attrs['_key_serializer'] = key_serializer + attrs['_clustering_keys'] = clustering_keys + attrs['_has_counter'] = len(counter_columns) > 0 + + # add polymorphic management attributes + attrs['_is_polymorphic_base'] = is_polymorphic_base + attrs['_is_polymorphic'] = is_polymorphic + attrs['_polymorphic_base'] = polymorphic_base + attrs['_discriminator_column'] = discriminator_column + attrs['_discriminator_column_name'] = discriminator_column_name + attrs['_discriminator_map'] = {} if is_polymorphic_base else None + + # setup class exceptions + DoesNotExistBase = None + for base in bases: + DoesNotExistBase = getattr(base, 'DoesNotExist', None) + if DoesNotExistBase is not None: + break + + DoesNotExistBase = DoesNotExistBase or attrs.pop('DoesNotExist', BaseModel.DoesNotExist) + attrs['DoesNotExist'] = type('DoesNotExist', (DoesNotExistBase,), {}) + + MultipleObjectsReturnedBase = None + for base in bases: + MultipleObjectsReturnedBase = getattr(base, 'MultipleObjectsReturned', None) + if MultipleObjectsReturnedBase is not None: + break + + MultipleObjectsReturnedBase = MultipleObjectsReturnedBase or attrs.pop('MultipleObjectsReturned', BaseModel.MultipleObjectsReturned) + attrs['MultipleObjectsReturned'] = type('MultipleObjectsReturned', (MultipleObjectsReturnedBase,), {}) + + # create the class and add a QuerySet to it + klass = super(ModelMetaClass, cls).__new__(cls, name, bases, attrs) + + udts = [] + for col in column_dict.values(): + columns.resolve_udts(col, udts) + + for user_type in set(udts): + user_type.register_for_keyspace(klass._get_keyspace()) + + return klass + + +class Model(BaseModel, metaclass=ModelMetaClass): + __abstract__ = True + """ + *Optional.* Indicates that this model is only intended to be used as a base class for other models. + You can't create tables for abstract models, but checks around schema validity are skipped during class construction. + """ + + __table_name__ = None + """ + *Optional.* Sets the name of the CQL table for this model. If left blank, the table name will be the name of the model, with it's module name as it's prefix. Manually defined table names are not inherited. + """ + + __table_name_case_sensitive__ = False + """ + *Optional.* By default, __table_name__ is case insensitive. Set this to True if you want to preserve the case sensitivity. + """ + + __keyspace__ = None + """ + Sets the name of the keyspace used by this model. + """ + + __connection__ = None + """ + Sets the name of the default connection used by this model. + """ + + __options__ = None + """ + *Optional* Table options applied with this model + + (e.g. compaction, default ttl, cache settings, tec.) + """ + + __discriminator_value__ = None + """ + *Optional* Specifies a value for the discriminator column when using model inheritance. + """ + + __compute_routing_key__ = True + """ + *Optional* Setting False disables computing the routing key for TokenAwareRouting + """ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/named.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/named.py new file mode 100644 index 0000000000000000000000000000000000000000..265d5c91e4086dc4daf9acf563f3a8c519b7cb77 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/named.py @@ -0,0 +1,169 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from cassandra.util import OrderedDict + +from cassandra.cqlengine import CQLEngineException +from cassandra.cqlengine.columns import Column +from cassandra.cqlengine.connection import get_cluster +from cassandra.cqlengine.models import UsingDescriptor, BaseModel +from cassandra.cqlengine.query import AbstractQueryableColumn, SimpleQuerySet +from cassandra.cqlengine.query import DoesNotExist as _DoesNotExist +from cassandra.cqlengine.query import MultipleObjectsReturned as _MultipleObjectsReturned + + +class QuerySetDescriptor(object): + """ + returns a fresh queryset for the given model + it's declared on everytime it's accessed + """ + + def __get__(self, obj, model): + """ :rtype: ModelQuerySet """ + if model.__abstract__: + raise CQLEngineException('cannot execute queries against abstract models') + return SimpleQuerySet(obj) + + def __call__(self, *args, **kwargs): + """ + Just a hint to IDEs that it's ok to call this + + :rtype: ModelQuerySet + """ + raise NotImplementedError + + +class NamedColumn(AbstractQueryableColumn): + """ + A column that is not coupled to a model class, or type + """ + + def __init__(self, name): + self.name = name + + def __unicode__(self): + return self.name + + def _get_column(self): + """ :rtype: NamedColumn """ + return self + + @property + def db_field_name(self): + return self.name + + @property + def cql(self): + return self.get_cql() + + def get_cql(self): + return '"{0}"'.format(self.name) + + def to_database(self, val): + return val + + +class NamedTable(object): + """ + A Table that is not coupled to a model class + """ + + __abstract__ = False + + objects = QuerySetDescriptor() + + __partition_keys = None + + _partition_key_index = None + + __connection__ = None + _connection = None + + using = UsingDescriptor() + + _get_connection = BaseModel._get_connection + + class DoesNotExist(_DoesNotExist): + pass + + class MultipleObjectsReturned(_MultipleObjectsReturned): + pass + + def __init__(self, keyspace, name): + self.keyspace = keyspace + self.name = name + self._connection = None + + @property + def _partition_keys(self): + if not self.__partition_keys: + self._get_partition_keys() + return self.__partition_keys + + def _get_partition_keys(self): + try: + table_meta = get_cluster(self._get_connection()).metadata.keyspaces[self.keyspace].tables[self.name] + self.__partition_keys = OrderedDict((pk.name, Column(primary_key=True, partition_key=True, db_field=pk.name)) for pk in table_meta.partition_key) + except Exception as e: + raise CQLEngineException("Failed inspecting partition keys for {0}." + "Ensure cqlengine is connected before attempting this with NamedTable.".format(self.column_family_name())) + + def column(self, name): + return NamedColumn(name) + + def column_family_name(self, include_keyspace=True): + """ + Returns the column family name if it's been defined + otherwise, it creates it from the module and class name + """ + if include_keyspace: + return '{0}.{1}'.format(self.keyspace, self.name) + else: + return self.name + + def _get_column(self, name): + """ + Returns the column matching the given name + + :rtype: Column + """ + return self.column(name) + + # def create(self, **kwargs): + # return self.objects.create(**kwargs) + + def all(self): + return self.objects.all() + + def filter(self, *args, **kwargs): + return self.objects.filter(*args, **kwargs) + + def get(self, *args, **kwargs): + return self.objects.get(*args, **kwargs) + + +class NamedKeyspace(object): + """ + A keyspace + """ + + def __init__(self, name): + self.name = name + + def table(self, name): + """ + returns a table descriptor with the given + name that belongs to this keyspace + """ + return NamedTable(self.name, name) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/operators.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/operators.py new file mode 100644 index 0000000000000000000000000000000000000000..2adf51758d855453406c81f321e3222a8d532609 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/operators.py @@ -0,0 +1,103 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from cassandra.cqlengine import UnicodeMixin + + +class QueryOperatorException(Exception): + pass + + +class BaseQueryOperator(UnicodeMixin): + # The symbol that identifies this operator in kwargs + # ie: colname__ + symbol = None + + # The comparator symbol this operator uses in cql + cql_symbol = None + + def __unicode__(self): + if self.cql_symbol is None: + raise QueryOperatorException("cql symbol is None") + return self.cql_symbol + + +class OpMapMeta(type): + + def __init__(cls, name, bases, dct): + if not hasattr(cls, 'opmap'): + cls.opmap = {} + else: + cls.opmap[cls.symbol] = cls + super(OpMapMeta, cls).__init__(name, bases, dct) + + +class BaseWhereOperator(BaseQueryOperator, metaclass=OpMapMeta): + """ base operator used for where clauses """ + @classmethod + def get_operator(cls, symbol): + try: + return cls.opmap[symbol.upper()] + except KeyError: + raise QueryOperatorException("{0} doesn't map to a QueryOperator".format(symbol)) + + +class EqualsOperator(BaseWhereOperator): + symbol = 'EQ' + cql_symbol = '=' + + +class NotEqualsOperator(BaseWhereOperator): + symbol = 'NE' + cql_symbol = '!=' + + +class InOperator(EqualsOperator): + symbol = 'IN' + cql_symbol = 'IN' + + +class GreaterThanOperator(BaseWhereOperator): + symbol = "GT" + cql_symbol = '>' + + +class GreaterThanOrEqualOperator(BaseWhereOperator): + symbol = "GTE" + cql_symbol = '>=' + + +class LessThanOperator(BaseWhereOperator): + symbol = "LT" + cql_symbol = '<' + + +class LessThanOrEqualOperator(BaseWhereOperator): + symbol = "LTE" + cql_symbol = '<=' + + +class ContainsOperator(EqualsOperator): + symbol = "CONTAINS" + cql_symbol = 'CONTAINS' + + +class LikeOperator(EqualsOperator): + symbol = "LIKE" + cql_symbol = 'LIKE' + + +class IsNotNullOperator(EqualsOperator): + symbol = "IS NOT NULL" + cql_symbol = 'IS NOT NULL' diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/query.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/query.py new file mode 100644 index 0000000000000000000000000000000000000000..afc7ceeef6b5210ab614204627552f19e178f4b3 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/query.py @@ -0,0 +1,1530 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import copy +from datetime import datetime, timedelta +from functools import partial +import time +from warnings import warn + +from cassandra.query import SimpleStatement, BatchType as CBatchType, BatchStatement +from cassandra.cqlengine import columns, CQLEngineException, ValidationError, UnicodeMixin +from cassandra.cqlengine import connection as conn +from cassandra.cqlengine.functions import Token, BaseQueryFunction, QueryValue +from cassandra.cqlengine.operators import (InOperator, EqualsOperator, GreaterThanOperator, + GreaterThanOrEqualOperator, LessThanOperator, + LessThanOrEqualOperator, ContainsOperator, BaseWhereOperator) +from cassandra.cqlengine.statements import (WhereClause, SelectStatement, DeleteStatement, + UpdateStatement, InsertStatement, + BaseCQLStatement, MapDeleteClause, ConditionalClause) + + +class QueryException(CQLEngineException): + pass + + +class IfNotExistsWithCounterColumn(CQLEngineException): + pass + + +class IfExistsWithCounterColumn(CQLEngineException): + pass + + +class LWTException(CQLEngineException): + """Lightweight conditional exception. + + This exception will be raised when a write using an `IF` clause could not be + applied due to existing data violating the condition. The existing data is + available through the ``existing`` attribute. + + :param existing: The current state of the data which prevented the write. + """ + def __init__(self, existing): + super(LWTException, self).__init__("LWT Query was not applied") + self.existing = existing + + +class DoesNotExist(QueryException): + pass + + +class MultipleObjectsReturned(QueryException): + pass + + +def check_applied(result): + """ + Raises LWTException if it looks like a failed LWT request. A LWTException + won't be raised in the special case in which there are several failed LWT + in a :class:`~cqlengine.query.BatchQuery`. + """ + try: + applied = result.was_applied + except Exception: + applied = True # result was not LWT form + if not applied: + raise LWTException(result.one()) + + +class AbstractQueryableColumn(UnicodeMixin): + """ + exposes cql query operators through pythons + builtin comparator symbols + """ + + def _get_column(self): + raise NotImplementedError + + def __unicode__(self): + raise NotImplementedError + + def _to_database(self, val): + if isinstance(val, QueryValue): + return val + else: + return self._get_column().to_database(val) + + def in_(self, item): + """ + Returns an in operator + + used where you'd typically want to use python's `in` operator + """ + return WhereClause(str(self), InOperator(), item) + + def contains_(self, item): + """ + Returns a CONTAINS operator + """ + return WhereClause(str(self), ContainsOperator(), item) + + + def __eq__(self, other): + return WhereClause(str(self), EqualsOperator(), self._to_database(other)) + + def __gt__(self, other): + return WhereClause(str(self), GreaterThanOperator(), self._to_database(other)) + + def __ge__(self, other): + return WhereClause(str(self), GreaterThanOrEqualOperator(), self._to_database(other)) + + def __lt__(self, other): + return WhereClause(str(self), LessThanOperator(), self._to_database(other)) + + def __le__(self, other): + return WhereClause(str(self), LessThanOrEqualOperator(), self._to_database(other)) + + +class BatchType(object): + Unlogged = 'UNLOGGED' + Counter = 'COUNTER' + + +class BatchQuery(object): + """ + Handles the batching of queries + + http://docs.datastax.com/en/cql/3.0/cql/cql_reference/batch_r.html + + See :doc:`/cqlengine/batches` for more details. + """ + warn_multiple_exec = True + + _consistency = None + + _connection = None + _connection_explicit = False + + + def __init__(self, batch_type=None, timestamp=None, consistency=None, execute_on_exception=False, + timeout=conn.NOT_SET, connection=None): + """ + :param batch_type: (optional) One of batch type values available through BatchType enum + :type batch_type: BatchType, str or None + :param timestamp: (optional) A datetime or timedelta object with desired timestamp to be applied + to the batch conditional. + :type timestamp: datetime or timedelta or None + :param consistency: (optional) One of consistency values ("ANY", "ONE", "QUORUM" etc) + :type consistency: The :class:`.ConsistencyLevel` to be used for the batch query, or None. + :param execute_on_exception: (Defaults to False) Indicates that when the BatchQuery instance is used + as a context manager the queries accumulated within the context must be executed despite + encountering an error within the context. By default, any exception raised from within + the context scope will cause the batched queries not to be executed. + :type execute_on_exception: bool + :param timeout: (optional) Timeout for the entire batch (in seconds), if not specified fallback + to default session timeout + :type timeout: float or None + :param str connection: Connection name to use for the batch execution + """ + self.queries = [] + self.batch_type = batch_type + if timestamp is not None and not isinstance(timestamp, (datetime, timedelta)): + raise CQLEngineException('timestamp object must be an instance of datetime') + self.timestamp = timestamp + self._consistency = consistency + self._execute_on_exception = execute_on_exception + self._timeout = timeout + self._callbacks = [] + self._executed = False + self._context_entered = False + self._connection = connection + if connection: + self._connection_explicit = True + + def add_query(self, query): + if not isinstance(query, BaseCQLStatement): + raise CQLEngineException('only BaseCQLStatements can be added to a batch query') + self.queries.append(query) + + def consistency(self, consistency): + self._consistency = consistency + + def _execute_callbacks(self): + for callback, args, kwargs in self._callbacks: + callback(*args, **kwargs) + + def add_callback(self, fn, *args, **kwargs): + """Add a function and arguments to be passed to it to be executed after the batch executes. + + A batch can support multiple callbacks. + + Note, that if the batch does not execute, the callbacks are not executed. + A callback, thus, is an "on batch success" handler. + + :param fn: Callable object + :type fn: callable + :param args: Positional arguments to be passed to the callback at the time of execution + :param kwargs: Named arguments to be passed to the callback at the time of execution + """ + if not callable(fn): + raise ValueError("Value for argument 'fn' is {0} and is not a callable object.".format(type(fn))) + self._callbacks.append((fn, args, kwargs)) + + def execute(self): + if self._executed and self.warn_multiple_exec: + msg = "Batch executed multiple times." + if self._context_entered: + msg += " If using the batch as a context manager, there is no need to call execute directly." + warn(msg) + self._executed = True + + if len(self.queries) == 0: + # Empty batch is a no-op + # except for callbacks + self._execute_callbacks() + return + + batch_type = None if self.batch_type is CBatchType.LOGGED else self.batch_type + opener = 'BEGIN ' + (str(batch_type) + ' ' if batch_type else '') + ' BATCH' + if self.timestamp: + + if isinstance(self.timestamp, int): + ts = self.timestamp + elif isinstance(self.timestamp, (datetime, timedelta)): + ts = self.timestamp + if isinstance(self.timestamp, timedelta): + ts += datetime.now() # Apply timedelta + ts = int(time.mktime(ts.timetuple()) * 1e+6 + ts.microsecond) + else: + raise ValueError("Batch expects a long, a timedelta, or a datetime") + + opener += ' USING TIMESTAMP {0}'.format(ts) + + query_list = [opener] + parameters = {} + ctx_counter = 0 + for query in self.queries: + query.update_context_id(ctx_counter) + ctx = query.get_context() + ctx_counter += len(ctx) + query_list.append(' ' + str(query)) + parameters.update(ctx) + + query_list.append('APPLY BATCH;') + + tmp = conn.execute('\n'.join(query_list), parameters, self._consistency, self._timeout, connection=self._connection) + check_applied(tmp) + + self.queries = [] + self._execute_callbacks() + + def __enter__(self): + self._context_entered = True + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + # don't execute if there was an exception by default + if exc_type is not None and not self._execute_on_exception: + return + self.execute() + + +class ContextQuery(object): + """ + A Context manager to allow a Model to switch context easily. Presently, the context only + specifies a keyspace for model IO. + + :param args: One or more models. A model should be a class type, not an instance. + :param kwargs: (optional) Context parameters: can be *keyspace* or *connection* + + For example: + + .. code-block:: python + + with ContextQuery(Automobile, keyspace='test2') as A: + A.objects.create(manufacturer='honda', year=2008, model='civic') + print(len(A.objects.all())) # 1 result + + with ContextQuery(Automobile, keyspace='test4') as A: + print(len(A.objects.all())) # 0 result + + # Multiple models + with ContextQuery(Automobile, Automobile2, connection='cluster2') as (A, A2): + print(len(A.objects.all())) + print(len(A2.objects.all())) + + """ + + def __init__(self, *args, **kwargs): + from cassandra.cqlengine import models + + self.models = [] + + if len(args) < 1: + raise ValueError("No model provided.") + + keyspace = kwargs.pop('keyspace', None) + connection = kwargs.pop('connection', None) + + if kwargs: + raise ValueError("Unknown keyword argument(s): {0}".format( + ','.join(kwargs.keys()))) + + for model in args: + try: + issubclass(model, models.Model) + except TypeError: + raise ValueError("Models must be derived from base Model.") + + m = models._clone_model_class(model, {}) + + if keyspace: + m.__keyspace__ = keyspace + if connection: + m.__connection__ = connection + + self.models.append(m) + + def __enter__(self): + if len(self.models) > 1: + return tuple(self.models) + return self.models[0] + + def __exit__(self, exc_type, exc_val, exc_tb): + return + + +class AbstractQuerySet(object): + + def __init__(self, model): + super(AbstractQuerySet, self).__init__() + self.model = model + + # Where clause filters + self._where = [] + + # Conditional clause filters + self._conditional = [] + + # ordering arguments + self._order = [] + + self._allow_filtering = False + + # CQL has a default limit of 10000, it's defined here + # because explicit is better than implicit + self._limit = 10000 + + # We store the fields for which we use the Equal operator + # in a query, so we don't select it from the DB. _defer_fields + # will contain the names of the fields in the DB, not the names + # of the variables used by the mapper + self._defer_fields = set() + self._deferred_values = {} + + # This variable will hold the names in the database of the fields + # for which we want to query + self._only_fields = [] + + self._values_list = False + self._flat_values_list = False + + # results cache + self._result_cache = None + self._result_idx = None + self._result_generator = None + self._materialize_results = True + + self._distinct_fields = None + + self._count = None + + self._batch = None + self._ttl = None + self._consistency = None + self._timestamp = None + self._if_not_exists = False + self._timeout = conn.NOT_SET + self._if_exists = False + self._fetch_size = None + self._connection = None + + @property + def column_family_name(self): + return self.model.column_family_name() + + def _execute(self, statement): + if self._batch: + return self._batch.add_query(statement) + else: + connection = self._connection or self.model._get_connection() + result = _execute_statement(self.model, statement, self._consistency, self._timeout, connection=connection) + if self._if_not_exists or self._if_exists or self._conditional: + check_applied(result) + return result + + def __unicode__(self): + return str(self._select_query()) + + def __str__(self): + return str(self.__unicode__()) + + def __call__(self, *args, **kwargs): + return self.filter(*args, **kwargs) + + def __deepcopy__(self, memo): + clone = self.__class__(self.model) + for k, v in self.__dict__.items(): + if k in ['_con', '_cur', '_result_cache', '_result_idx', '_result_generator', '_construct_result']: # don't clone these, which are per-request-execution + clone.__dict__[k] = None + elif k == '_batch': + # we need to keep the same batch instance across + # all queryset clones, otherwise the batched queries + # fly off into other batch instances which are never + # executed, thx @dokai + clone.__dict__[k] = self._batch + elif k == '_timeout': + clone.__dict__[k] = self._timeout + else: + clone.__dict__[k] = copy.deepcopy(v, memo) + + return clone + + def __len__(self): + self._execute_query() + return self.count() + + # ----query generation / execution---- + + def _select_fields(self): + """ returns the fields to select """ + return [] + + def _validate_select_where(self): + """ put select query validation here """ + + def _select_query(self): + """ + Returns a select clause based on the given filter args + """ + if self._where: + self._validate_select_where() + return SelectStatement( + self.column_family_name, + fields=self._select_fields(), + where=self._where, + order_by=self._order, + limit=self._limit, + allow_filtering=self._allow_filtering, + distinct_fields=self._distinct_fields, + fetch_size=self._fetch_size + ) + + # ----Reads------ + + def _execute_query(self): + if self._batch: + raise CQLEngineException("Only inserts, updates, and deletes are available in batch mode") + if self._result_cache is None: + self._result_generator = (i for i in self._execute(self._select_query())) + self._result_cache = [] + self._construct_result = self._maybe_inject_deferred(self._get_result_constructor()) + + # "DISTINCT COUNT()" is not supported in C* < 2.2, so we need to materialize all results to get + # len() and count() working with DISTINCT queries + if self._materialize_results or self._distinct_fields: + self._fill_result_cache() + + def _fill_result_cache(self): + """ + Fill the result cache with all results. + """ + + idx = 0 + try: + while True: + idx += 1000 + self._fill_result_cache_to_idx(idx) + except StopIteration: + pass + + self._count = len(self._result_cache) + + def _fill_result_cache_to_idx(self, idx): + self._execute_query() + if self._result_idx is None: + self._result_idx = -1 + + qty = idx - self._result_idx + if qty < 1: + return + else: + for idx in range(qty): + self._result_idx += 1 + while True: + try: + self._result_cache[self._result_idx] = self._construct_result(self._result_cache[self._result_idx]) + break + except IndexError: + self._result_cache.append(next(self._result_generator)) + + def __iter__(self): + self._execute_query() + + idx = 0 + while True: + if len(self._result_cache) <= idx: + try: + self._result_cache.append(next(self._result_generator)) + except StopIteration: + break + + instance = self._result_cache[idx] + if isinstance(instance, dict): + self._fill_result_cache_to_idx(idx) + yield self._result_cache[idx] + + idx += 1 + + def __getitem__(self, s): + self._execute_query() + + if isinstance(s, slice): + start = s.start if s.start else 0 + + if start < 0 or (s.stop is not None and s.stop < 0): + warn("ModelQuerySet slicing with negative indices support will be removed in 4.0.", + DeprecationWarning) + + # calculate the amount of results that need to be loaded + end = s.stop + if start < 0 or s.stop is None or s.stop < 0: + end = self.count() + + try: + self._fill_result_cache_to_idx(end) + except StopIteration: + pass + + return self._result_cache[start:s.stop:s.step] + else: + try: + s = int(s) + except (ValueError, TypeError): + raise TypeError('QuerySet indices must be integers') + + if s < 0: + warn("ModelQuerySet indexing with negative indices support will be removed in 4.0.", + DeprecationWarning) + + # Using negative indexing is costly since we have to execute a count() + if s < 0: + num_results = self.count() + s += num_results + + try: + self._fill_result_cache_to_idx(s) + except StopIteration: + raise IndexError + + return self._result_cache[s] + + def _get_result_constructor(self): + """ + Returns a function that will be used to instantiate query results + """ + raise NotImplementedError + + @staticmethod + def _construct_with_deferred(f, deferred, row): + row.update(deferred) + return f(row) + + def _maybe_inject_deferred(self, constructor): + return partial(self._construct_with_deferred, constructor, self._deferred_values)\ + if self._deferred_values else constructor + + def batch(self, batch_obj): + """ + Set a batch object to run the query on. + + Note: running a select query with a batch object will raise an exception + """ + if self._connection: + raise CQLEngineException("Cannot specify the connection on model in batch mode.") + + if batch_obj is not None and not isinstance(batch_obj, BatchQuery): + raise CQLEngineException('batch_obj must be a BatchQuery instance or None') + clone = copy.deepcopy(self) + clone._batch = batch_obj + return clone + + def first(self): + try: + return next(iter(self)) + except StopIteration: + return None + + def all(self): + """ + Returns a queryset matching all rows + + .. code-block:: python + + for user in User.objects().all(): + print(user) + """ + return copy.deepcopy(self) + + def consistency(self, consistency): + """ + Sets the consistency level for the operation. See :class:`.ConsistencyLevel`. + + .. code-block:: python + + for user in User.objects(id=3).consistency(CL.ONE): + print(user) + """ + clone = copy.deepcopy(self) + clone._consistency = consistency + return clone + + def _parse_filter_arg(self, arg): + """ + Parses a filter arg in the format: + __ + :returns: colname, op tuple + """ + statement = arg.rsplit('__', 1) + if len(statement) == 1: + return arg, None + elif len(statement) == 2: + return (statement[0], statement[1]) if arg != 'pk__token' else (arg, None) + else: + raise QueryException("Can't parse '{0}'".format(arg)) + + def iff(self, *args, **kwargs): + """Adds IF statements to queryset""" + if len([x for x in kwargs.values() if x is None]): + raise CQLEngineException("None values on iff are not allowed") + + clone = copy.deepcopy(self) + for operator in args: + if not isinstance(operator, ConditionalClause): + raise QueryException('{0} is not a valid query operator'.format(operator)) + clone._conditional.append(operator) + + for arg, val in kwargs.items(): + if isinstance(val, Token): + raise QueryException("Token() values are not valid in conditionals") + + col_name, col_op = self._parse_filter_arg(arg) + try: + column = self.model._get_column(col_name) + except KeyError: + raise QueryException("Can't resolve column name: '{0}'".format(col_name)) + + if isinstance(val, BaseQueryFunction): + query_val = val + else: + query_val = column.to_database(val) + + operator_class = BaseWhereOperator.get_operator(col_op or 'EQ') + operator = operator_class() + clone._conditional.append(WhereClause(column.db_field_name, operator, query_val)) + + return clone + + def filter(self, *args, **kwargs): + """ + Adds WHERE arguments to the queryset, returning a new queryset + + See :ref:`retrieving-objects-with-filters` + + Returns a QuerySet filtered on the keyword arguments + """ + # add arguments to the where clause filters + if len([x for x in kwargs.values() if x is None]): + raise CQLEngineException("None values on filter are not allowed") + + clone = copy.deepcopy(self) + for operator in args: + if not isinstance(operator, WhereClause): + raise QueryException('{0} is not a valid query operator'.format(operator)) + clone._where.append(operator) + + for arg, val in kwargs.items(): + col_name, col_op = self._parse_filter_arg(arg) + quote_field = True + + if not isinstance(val, Token): + try: + column = self.model._get_column(col_name) + except KeyError: + raise QueryException("Can't resolve column name: '{0}'".format(col_name)) + else: + if col_name != 'pk__token': + raise QueryException("Token() values may only be compared to the 'pk__token' virtual column") + + column = columns._PartitionKeysToken(self.model) + quote_field = False + + partition_columns = column.partition_columns + if len(partition_columns) != len(val.value): + raise QueryException( + 'Token() received {0} arguments but model has {1} partition keys'.format( + len(val.value), len(partition_columns))) + val.set_columns(partition_columns) + + # get query operator, or use equals if not supplied + operator_class = BaseWhereOperator.get_operator(col_op or 'EQ') + operator = operator_class() + + if isinstance(operator, InOperator): + if not isinstance(val, (list, tuple)): + raise QueryException('IN queries must use a list/tuple value') + query_val = [column.to_database(v) for v in val] + elif isinstance(val, BaseQueryFunction): + query_val = val + elif (isinstance(operator, ContainsOperator) and + isinstance(column, (columns.List, columns.Set, columns.Map))): + # For ContainsOperator and collections, we query using the value, not the container + query_val = val + else: + query_val = column.to_database(val) + if not col_op: # only equal values should be deferred + clone._defer_fields.add(column.db_field_name) + clone._deferred_values[column.db_field_name] = val # map by db field name for substitution in results + + clone._where.append(WhereClause(column.db_field_name, operator, query_val, quote_field=quote_field)) + + return clone + + def get(self, *args, **kwargs): + """ + Returns a single instance matching this query, optionally with additional filter kwargs. + + See :ref:`retrieving-objects-with-filters` + + Returns a single object matching the QuerySet. + + .. code-block:: python + + user = User.get(id=1) + + If no objects are matched, a :class:`~.DoesNotExist` exception is raised. + + If more than one object is found, a :class:`~.MultipleObjectsReturned` exception is raised. + """ + if args or kwargs: + return self.filter(*args, **kwargs).get() + + self._execute_query() + + # Check that the resultset only contains one element, avoiding sending a COUNT query + try: + self[1] + raise self.model.MultipleObjectsReturned('Multiple objects found') + except IndexError: + pass + + try: + obj = self[0] + except IndexError: + raise self.model.DoesNotExist + + return obj + + def _get_ordering_condition(self, colname): + order_type = 'DESC' if colname.startswith('-') else 'ASC' + colname = colname.replace('-', '') + + return colname, order_type + + def order_by(self, *colnames): + """ + Sets the column(s) to be used for ordering + + Default order is ascending, prepend a '-' to any column name for descending + + *Note: column names must be a clustering key* + + .. code-block:: python + + from uuid import uuid1,uuid4 + + class Comment(Model): + photo_id = UUID(primary_key=True) + comment_id = TimeUUID(primary_key=True, default=uuid1) # second primary key component is a clustering key + comment = Text() + + sync_table(Comment) + + u = uuid4() + for x in range(5): + Comment.create(photo_id=u, comment="test %d" % x) + + print("Normal") + for comment in Comment.objects(photo_id=u): + print(comment.comment_id) + + print("Reversed") + for comment in Comment.objects(photo_id=u).order_by("-comment_id"): + print(comment.comment_id) + """ + if len(colnames) == 0: + clone = copy.deepcopy(self) + clone._order = [] + return clone + + conditions = [] + for colname in colnames: + conditions.append('"{0}" {1}'.format(*self._get_ordering_condition(colname))) + + clone = copy.deepcopy(self) + clone._order.extend(conditions) + return clone + + def count(self): + """ + Returns the number of rows matched by this query. + + *Note: This function executes a SELECT COUNT() and has a performance cost on large datasets* + """ + if self._batch: + raise CQLEngineException("Only inserts, updates, and deletes are available in batch mode") + + if self._count is None: + query = self._select_query() + query.count = True + result = self._execute(query) + count_row = result.one().popitem() + self._count = count_row[1] + return self._count + + def distinct(self, distinct_fields=None): + """ + Returns the DISTINCT rows matched by this query. + + distinct_fields default to the partition key fields if not specified. + + *Note: distinct_fields must be a partition key or a static column* + + .. code-block:: python + + class Automobile(Model): + manufacturer = columns.Text(partition_key=True) + year = columns.Integer(primary_key=True) + model = columns.Text(primary_key=True) + price = columns.Decimal() + + sync_table(Automobile) + + # create rows + + Automobile.objects.distinct() + + # or + + Automobile.objects.distinct(['manufacturer']) + + """ + + clone = copy.deepcopy(self) + if distinct_fields: + clone._distinct_fields = distinct_fields + else: + clone._distinct_fields = [x.column_name for x in self.model._partition_keys.values()] + + return clone + + def limit(self, v): + """ + Limits the number of results returned by Cassandra. Use *0* or *None* to disable. + + *Note that CQL's default limit is 10,000, so all queries without a limit set explicitly will have an implicit limit of 10,000* + + .. code-block:: python + + # Fetch 100 users + for user in User.objects().limit(100): + print(user) + + # Fetch all users + for user in User.objects().limit(None): + print(user) + """ + + if v is None: + v = 0 + + if not isinstance(v, int): + raise TypeError + if v == self._limit: + return self + + if v < 0: + raise QueryException("Negative limit is not allowed") + + clone = copy.deepcopy(self) + clone._limit = v + return clone + + def fetch_size(self, v): + """ + Sets the number of rows that are fetched at a time. + + *Note that driver's default fetch size is 5000.* + + .. code-block:: python + + for user in User.objects().fetch_size(500): + print(user) + """ + + if not isinstance(v, int): + raise TypeError + if v == self._fetch_size: + return self + + if v < 1: + raise QueryException("fetch size less than 1 is not allowed") + + clone = copy.deepcopy(self) + clone._fetch_size = v + return clone + + def allow_filtering(self): + """ + Enables the (usually) unwise practive of querying on a clustering key without also defining a partition key + """ + clone = copy.deepcopy(self) + clone._allow_filtering = True + return clone + + def _only_or_defer(self, action, fields): + if action == 'only' and self._only_fields: + raise QueryException("QuerySet already has 'only' fields defined") + + clone = copy.deepcopy(self) + + # check for strange fields + missing_fields = [f for f in fields if f not in self.model._columns.keys()] + if missing_fields: + raise QueryException( + "Can't resolve fields {0} in {1}".format( + ', '.join(missing_fields), self.model.__name__)) + + fields = [self.model._columns[field].db_field_name for field in fields] + + if action == 'defer': + clone._defer_fields.update(fields) + elif action == 'only': + clone._only_fields = fields + else: + raise ValueError + + return clone + + def only(self, fields): + """ Load only these fields for the returned query """ + return self._only_or_defer('only', fields) + + def defer(self, fields): + """ Don't load these fields for the returned query """ + return self._only_or_defer('defer', fields) + + def create(self, **kwargs): + return self.model(**kwargs) \ + .batch(self._batch) \ + .ttl(self._ttl) \ + .consistency(self._consistency) \ + .if_not_exists(self._if_not_exists) \ + .timestamp(self._timestamp) \ + .if_exists(self._if_exists) \ + .using(connection=self._connection) \ + .save() + + def delete(self): + """ + Deletes the contents of a query + """ + # validate where clause + partition_keys = set(x.db_field_name for x in self.model._partition_keys.values()) + if partition_keys - set(c.field for c in self._where): + raise QueryException("The partition key must be defined on delete queries") + + dq = DeleteStatement( + self.column_family_name, + where=self._where, + timestamp=self._timestamp, + conditionals=self._conditional, + if_exists=self._if_exists + ) + self._execute(dq) + + def __eq__(self, q): + if len(self._where) == len(q._where): + return all([w in q._where for w in self._where]) + return False + + def __ne__(self, q): + return not (self != q) + + def timeout(self, timeout): + """ + :param timeout: Timeout for the query (in seconds) + :type timeout: float or None + """ + clone = copy.deepcopy(self) + clone._timeout = timeout + return clone + + def using(self, keyspace=None, connection=None): + """ + Change the context on-the-fly of the Model class (keyspace, connection) + """ + + if connection and self._batch: + raise CQLEngineException("Cannot specify a connection on model in batch mode.") + + clone = copy.deepcopy(self) + if keyspace: + from cassandra.cqlengine.models import _clone_model_class + clone.model = _clone_model_class(self.model, {'__keyspace__': keyspace}) + + if connection: + clone._connection = connection + + return clone + + +class ResultObject(dict): + """ + adds attribute access to a dictionary + """ + + def __getattr__(self, item): + try: + return self[item] + except KeyError: + raise AttributeError + + +class SimpleQuerySet(AbstractQuerySet): + """ + Overrides _get_result_constructor for querysets that do not define a model (e.g. NamedTable queries) + """ + + def _get_result_constructor(self): + """ + Returns a function that will be used to instantiate query results + """ + return ResultObject + + +class ModelQuerySet(AbstractQuerySet): + """ + """ + def _validate_select_where(self): + """ Checks that a filterset will not create invalid select statement """ + # check that there's either a =, a IN or a CONTAINS (collection) + # relationship with a primary key or indexed field. We also allow + # custom indexes to be queried with any operator (a difference + # between a secondary index) + equal_ops = [self.model._get_column_by_db_name(w.field) \ + for w in self._where if not isinstance(w.value, Token) + and (isinstance(w.operator, EqualsOperator) + or self.model._get_column_by_db_name(w.field).custom_index)] + token_comparison = any([w for w in self._where if isinstance(w.value, Token)]) + if not any(w.primary_key or w.has_index for w in equal_ops) and not token_comparison and not self._allow_filtering: + raise QueryException( + ('Where clauses require either =, a IN or a CONTAINS ' + '(collection) comparison with either a primary key or ' + 'indexed field. You might want to consider setting ' + 'custom_index on fields that you manage index outside ' + 'cqlengine.')) + + if not self._allow_filtering: + # if the query is not on an indexed field + if not any(w.has_index for w in equal_ops): + if not any([w.partition_key for w in equal_ops]) and not token_comparison: + raise QueryException( + ('Filtering on a clustering key without a partition ' + 'key is not allowed unless allow_filtering() is ' + 'called on the queryset. You might want to consider ' + 'setting custom_index on fields that you manage ' + 'index outside cqlengine.')) + + def _select_fields(self): + if self._defer_fields or self._only_fields: + fields = [columns.db_field_name for columns in self.model._columns.values()] + if self._defer_fields: + fields = [f for f in fields if f not in self._defer_fields] + # select the partition keys if all model fields are set defer + if not fields: + fields = [columns.db_field_name for columns in self.model._partition_keys.values()] + if self._only_fields: + fields = [f for f in fields if f in self._only_fields] + if not fields: + raise QueryException('No fields in select query. Only fields: "{0}", defer fields: "{1}"'.format( + ','.join(self._only_fields), ','.join(self._defer_fields))) + return fields + return super(ModelQuerySet, self)._select_fields() + + def _get_result_constructor(self): + """ Returns a function that will be used to instantiate query results """ + if not self._values_list: # we want models + return self.model._construct_instance + elif self._flat_values_list: # the user has requested flattened list (1 value per row) + key = self._only_fields[0] + return lambda row: row[key] + else: + return lambda row: [row[f] for f in self._only_fields] + + def _get_ordering_condition(self, colname): + colname, order_type = super(ModelQuerySet, self)._get_ordering_condition(colname) + + column = self.model._columns.get(colname) + if column is None: + raise QueryException("Can't resolve the column name: '{0}'".format(colname)) + + # validate the column selection + if not column.primary_key: + raise QueryException( + "Can't order on '{0}', can only order on (clustered) primary keys".format(colname)) + + pks = [v for k, v in self.model._columns.items() if v.primary_key] + if column == pks[0]: + raise QueryException( + "Can't order by the first primary key (partition key), clustering (secondary) keys only") + + return column.db_field_name, order_type + + def values_list(self, *fields, **kwargs): + """ Instructs the query set to return tuples, not model instance """ + flat = kwargs.pop('flat', False) + if kwargs: + raise TypeError('Unexpected keyword arguments to values_list: %s' + % (kwargs.keys(),)) + if flat and len(fields) > 1: + raise TypeError("'flat' is not valid when values_list is called with more than one field.") + clone = self.only(fields) + clone._values_list = True + clone._flat_values_list = flat + return clone + + def ttl(self, ttl): + """ + Sets the ttl (in seconds) for modified data. + + *Note that running a select query with a ttl value will raise an exception* + """ + clone = copy.deepcopy(self) + clone._ttl = ttl + return clone + + def timestamp(self, timestamp): + """ + Allows for custom timestamps to be saved with the record. + """ + clone = copy.deepcopy(self) + clone._timestamp = timestamp + return clone + + def if_not_exists(self): + """ + Check the existence of an object before insertion. + + If the insertion isn't applied, a LWTException is raised. + """ + if self.model._has_counter: + raise IfNotExistsWithCounterColumn('if_not_exists cannot be used with tables containing counter columns') + clone = copy.deepcopy(self) + clone._if_not_exists = True + return clone + + def if_exists(self): + """ + Check the existence of an object before an update or delete. + + If the update or delete isn't applied, a LWTException is raised. + """ + if self.model._has_counter: + raise IfExistsWithCounterColumn('if_exists cannot be used with tables containing counter columns') + clone = copy.deepcopy(self) + clone._if_exists = True + return clone + + def update(self, **values): + """ + Performs an update on the row selected by the queryset. Include values to update in the + update like so: + + .. code-block:: python + + Model.objects(key=n).update(value='x') + + Passing in updates for columns which are not part of the model will raise a ValidationError. + + Per column validation will be performed, but instance level validation will not + (i.e., `Model.validate` is not called). This is sometimes referred to as a blind update. + + For example: + + .. code-block:: python + + class User(Model): + id = Integer(primary_key=True) + name = Text() + + setup(["localhost"], "test") + sync_table(User) + + u = User.create(id=1, name="jon") + + User.objects(id=1).update(name="Steve") + + # sets name to null + User.objects(id=1).update(name=None) + + + Also supported is blindly adding and removing elements from container columns, + without loading a model instance from Cassandra. + + Using the syntax `.update(column_name={x, y, z})` will overwrite the contents of the container, like updating a + non container column. However, adding `__` to the end of the keyword arg, makes the update call add + or remove items from the collection, without overwriting then entire column. + + Given the model below, here are the operations that can be performed on the different container columns: + + .. code-block:: python + + class Row(Model): + row_id = columns.Integer(primary_key=True) + set_column = columns.Set(Integer) + list_column = columns.List(Integer) + map_column = columns.Map(Integer, Integer) + + :class:`~cqlengine.columns.Set` + + - `add`: adds the elements of the given set to the column + - `remove`: removes the elements of the given set to the column + + + .. code-block:: python + + # add elements to a set + Row.objects(row_id=5).update(set_column__add={6}) + + # remove elements to a set + Row.objects(row_id=5).update(set_column__remove={4}) + + :class:`~cqlengine.columns.List` + + - `append`: appends the elements of the given list to the end of the column + - `prepend`: prepends the elements of the given list to the beginning of the column + + .. code-block:: python + + # append items to a list + Row.objects(row_id=5).update(list_column__append=[6, 7]) + + # prepend items to a list + Row.objects(row_id=5).update(list_column__prepend=[1, 2]) + + + :class:`~cqlengine.columns.Map` + + - `update`: adds the given keys/values to the columns, creating new entries if they didn't exist, and overwriting old ones if they did + + .. code-block:: python + + # add items to a map + Row.objects(row_id=5).update(map_column__update={1: 2, 3: 4}) + + # remove items from a map + Row.objects(row_id=5).update(map_column__remove={1, 2}) + """ + if not values: + return + + nulled_columns = set() + updated_columns = set() + us = UpdateStatement(self.column_family_name, where=self._where, ttl=self._ttl, + timestamp=self._timestamp, conditionals=self._conditional, if_exists=self._if_exists) + for name, val in values.items(): + col_name, col_op = self._parse_filter_arg(name) + col = self.model._columns.get(col_name) + # check for nonexistant columns + if col is None: + raise ValidationError("{0}.{1} has no column named: {2}".format(self.__module__, self.model.__name__, col_name)) + # check for primary key update attempts + if col.is_primary_key: + raise ValidationError("Cannot apply update to primary key '{0}' for {1}.{2}".format(col_name, self.__module__, self.model.__name__)) + + if col_op == 'remove' and isinstance(col, columns.Map): + if not isinstance(val, set): + raise ValidationError( + "Cannot apply update operation '{0}' on column '{1}' with value '{2}'. A set is required.".format(col_op, col_name, val)) + val = {v: None for v in val} + else: + # we should not provide default values in this use case. + val = col.validate(val) + + if val is None: + nulled_columns.add(col_name) + continue + + us.add_update(col, val, operation=col_op) + updated_columns.add(col_name) + + if us.assignments: + self._execute(us) + + if nulled_columns: + delete_conditional = [condition for condition in self._conditional + if condition.field not in updated_columns] if self._conditional else None + ds = DeleteStatement(self.column_family_name, fields=nulled_columns, + where=self._where, conditionals=delete_conditional, if_exists=self._if_exists) + self._execute(ds) + + +class DMLQuery(object): + """ + A query object used for queries performing inserts, updates, or deletes + + this is usually instantiated by the model instance to be modified + + unlike the read query object, this is mutable + """ + _ttl = None + _consistency = None + _timestamp = None + _if_not_exists = False + _if_exists = False + + def __init__(self, model, instance=None, batch=None, ttl=None, consistency=None, timestamp=None, + if_not_exists=False, conditional=None, timeout=conn.NOT_SET, if_exists=False): + self.model = model + self.column_family_name = self.model.column_family_name() + self.instance = instance + self._batch = batch + self._ttl = ttl + self._consistency = consistency + self._timestamp = timestamp + self._if_not_exists = if_not_exists + self._if_exists = if_exists + self._conditional = conditional + self._timeout = timeout + + def _execute(self, statement): + connection = self.instance._get_connection() if self.instance else self.model._get_connection() + if self._batch: + if self._batch._connection: + if not self._batch._connection_explicit and connection and \ + connection != self._batch._connection: + raise CQLEngineException('BatchQuery queries must be executed on the same connection') + else: + # set the BatchQuery connection from the model + self._batch._connection = connection + return self._batch.add_query(statement) + else: + results = _execute_statement(self.model, statement, self._consistency, self._timeout, connection=connection) + if self._if_not_exists or self._if_exists or self._conditional: + check_applied(results) + return results + + def batch(self, batch_obj): + if batch_obj is not None and not isinstance(batch_obj, BatchQuery): + raise CQLEngineException('batch_obj must be a BatchQuery instance or None') + self._batch = batch_obj + return self + + def _delete_null_columns(self, conditionals=None): + """ + executes a delete query to remove columns that have changed to null + """ + ds = DeleteStatement(self.column_family_name, conditionals=conditionals, if_exists=self._if_exists) + deleted_fields = False + static_only = True + for _, v in self.instance._values.items(): + col = v.column + if v.deleted: + ds.add_field(col.db_field_name) + deleted_fields = True + static_only &= col.static + elif isinstance(col, columns.Map): + uc = MapDeleteClause(col.db_field_name, v.value, v.previous_value) + if uc.get_context_size() > 0: + ds.add_field(uc) + deleted_fields = True + static_only |= col.static + + if deleted_fields: + keys = self.model._partition_keys if static_only else self.model._primary_keys + for name, col in keys.items(): + ds.add_where(col, EqualsOperator(), getattr(self.instance, name)) + self._execute(ds) + + def update(self): + """ + updates a row. + This is a blind update call. + All validation and cleaning needs to happen + prior to calling this. + """ + if self.instance is None: + raise CQLEngineException("DML Query intance attribute is None") + assert type(self.instance) == self.model + null_clustering_key = False if len(self.instance._clustering_keys) == 0 else True + static_changed_only = True + statement = UpdateStatement(self.column_family_name, ttl=self._ttl, timestamp=self._timestamp, + conditionals=self._conditional, if_exists=self._if_exists) + for name, col in self.instance._clustering_keys.items(): + null_clustering_key = null_clustering_key and col._val_is_null(getattr(self.instance, name, None)) + + updated_columns = set() + # get defined fields and their column names + for name, col in self.model._columns.items(): + # if clustering key is null, don't include non static columns + if null_clustering_key and not col.static and not col.partition_key: + continue + if not col.is_primary_key: + val = getattr(self.instance, name, None) + val_mgr = self.instance._values[name] + + if val is None: + continue + + if not val_mgr.changed and not isinstance(col, columns.Counter): + continue + + static_changed_only = static_changed_only and col.static + statement.add_update(col, val, previous=val_mgr.previous_value) + updated_columns.add(col.db_field_name) + + if statement.assignments: + for name, col in self.model._primary_keys.items(): + # only include clustering key if clustering key is not null, and non static columns are changed to avoid cql error + if (null_clustering_key or static_changed_only) and (not col.partition_key): + continue + statement.add_where(col, EqualsOperator(), getattr(self.instance, name)) + self._execute(statement) + + if not null_clustering_key: + # remove conditions on fields that have been updated + delete_conditionals = [condition for condition in self._conditional + if condition.field not in updated_columns] if self._conditional else None + self._delete_null_columns(delete_conditionals) + + def save(self): + """ + Creates / updates a row. + This is a blind insert call. + All validation and cleaning needs to happen + prior to calling this. + """ + if self.instance is None: + raise CQLEngineException("DML Query intance attribute is None") + assert type(self.instance) == self.model + + nulled_fields = set() + if self.instance._has_counter or self.instance._can_update(): + if self.instance._has_counter: + warn("'create' and 'save' actions on Counters are deprecated. It will be disallowed in 4.0. " + "Use the 'update' mechanism instead.", DeprecationWarning) + return self.update() + else: + insert = InsertStatement(self.column_family_name, ttl=self._ttl, timestamp=self._timestamp, if_not_exists=self._if_not_exists) + static_save_only = False if len(self.instance._clustering_keys) == 0 else True + for name, col in self.instance._clustering_keys.items(): + static_save_only = static_save_only and col._val_is_null(getattr(self.instance, name, None)) + for name, col in self.instance._columns.items(): + if static_save_only and not col.static and not col.partition_key: + continue + val = getattr(self.instance, name, None) + if col._val_is_null(val): + if self.instance._values[name].changed: + nulled_fields.add(col.db_field_name) + continue + if col.has_default and not self.instance._values[name].changed: + # Ensure default columns included in a save() are marked as explicit, to get them *persisted* properly + self.instance._values[name].explicit = True + insert.add_assignment(col, getattr(self.instance, name, None)) + + # skip query execution if it's empty + # caused by pointless update queries + if not insert.is_empty: + self._execute(insert) + # delete any nulled columns + if not static_save_only: + self._delete_null_columns() + + def delete(self): + """ Deletes one instance """ + if self.instance is None: + raise CQLEngineException("DML Query instance attribute is None") + + ds = DeleteStatement(self.column_family_name, timestamp=self._timestamp, conditionals=self._conditional, if_exists=self._if_exists) + for name, col in self.model._primary_keys.items(): + val = getattr(self.instance, name) + if val is None and not col.partition_key: + continue + ds.add_where(col, EqualsOperator(), val) + self._execute(ds) + + +def _execute_statement(model, statement, consistency_level, timeout, connection=None): + params = statement.get_context() + s = SimpleStatement(str(statement), consistency_level=consistency_level, fetch_size=statement.fetch_size) + if model._partition_key_index: + key_values = statement.partition_key_values(model._partition_key_index) + if not any(v is None for v in key_values): + parts = model._routing_key_from_values(key_values, conn.get_cluster(connection).protocol_version) + s.routing_key = parts + s.keyspace = model._get_keyspace() + connection = connection or model._get_connection() + return conn.execute(s, params, timeout=timeout, connection=connection) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/statements.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/statements.py new file mode 100644 index 0000000000000000000000000000000000000000..4782fdccd80a39835dd9f9171869f46073e7ec9a --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/statements.py @@ -0,0 +1,907 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import datetime, timedelta +import time + +from cassandra.query import FETCH_SIZE_UNSET +from cassandra.cqlengine import columns +from cassandra.cqlengine import UnicodeMixin +from cassandra.cqlengine.functions import QueryValue +from cassandra.cqlengine.operators import BaseWhereOperator, InOperator, EqualsOperator, IsNotNullOperator + + +class StatementException(Exception): + pass + + +class ValueQuoter(UnicodeMixin): + + def __init__(self, value): + self.value = value + + def __unicode__(self): + from cassandra.encoder import cql_quote + if isinstance(self.value, (list, tuple)): + return '[' + ', '.join([cql_quote(v) for v in self.value]) + ']' + elif isinstance(self.value, dict): + return '{' + ', '.join([cql_quote(k) + ':' + cql_quote(v) for k, v in self.value.items()]) + '}' + elif isinstance(self.value, set): + return '{' + ', '.join([cql_quote(v) for v in self.value]) + '}' + return cql_quote(self.value) + + def __eq__(self, other): + if isinstance(other, self.__class__): + return self.value == other.value + return False + + +class InQuoter(ValueQuoter): + + def __unicode__(self): + from cassandra.encoder import cql_quote + return '(' + ', '.join([cql_quote(v) for v in self.value]) + ')' + + +class BaseClause(UnicodeMixin): + + def __init__(self, field, value): + self.field = field + self.value = value + self.context_id = None + + def __unicode__(self): + raise NotImplementedError + + def __hash__(self): + return hash(self.field) ^ hash(self.value) + + def __eq__(self, other): + if isinstance(other, self.__class__): + return self.field == other.field and self.value == other.value + return False + + def __ne__(self, other): + return not self.__eq__(other) + + def get_context_size(self): + """ returns the number of entries this clause will add to the query context """ + return 1 + + def set_context_id(self, i): + """ sets the value placeholder that will be used in the query """ + self.context_id = i + + def update_context(self, ctx): + """ updates the query context with this clauses values """ + assert isinstance(ctx, dict) + ctx[str(self.context_id)] = self.value + + +class WhereClause(BaseClause): + """ a single where statement used in queries """ + + def __init__(self, field, operator, value, quote_field=True): + """ + + :param field: + :param operator: + :param value: + :param quote_field: hack to get the token function rendering properly + :return: + """ + if not isinstance(operator, BaseWhereOperator): + raise StatementException( + "operator must be of type {0}, got {1}".format(BaseWhereOperator, type(operator)) + ) + super(WhereClause, self).__init__(field, value) + self.operator = operator + self.query_value = self.value if isinstance(self.value, QueryValue) else QueryValue(self.value) + self.quote_field = quote_field + + def __unicode__(self): + field = ('"{0}"' if self.quote_field else '{0}').format(self.field) + return u'{0} {1} {2}'.format(field, self.operator, str(self.query_value)) + + def __hash__(self): + return super(WhereClause, self).__hash__() ^ hash(self.operator) + + def __eq__(self, other): + if super(WhereClause, self).__eq__(other): + return self.operator.__class__ == other.operator.__class__ + return False + + def get_context_size(self): + return self.query_value.get_context_size() + + def set_context_id(self, i): + super(WhereClause, self).set_context_id(i) + self.query_value.set_context_id(i) + + def update_context(self, ctx): + if isinstance(self.operator, InOperator): + ctx[str(self.context_id)] = InQuoter(self.value) + else: + self.query_value.update_context(ctx) + + +class IsNotNullClause(WhereClause): + def __init__(self, field): + super(IsNotNullClause, self).__init__(field, IsNotNullOperator(), '') + + def __unicode__(self): + field = ('"{0}"' if self.quote_field else '{0}').format(self.field) + return u'{0} {1}'.format(field, self.operator) + + def update_context(self, ctx): + pass + + def get_context_size(self): + return 0 + +# alias for convenience +IsNotNull = IsNotNullClause + + +class AssignmentClause(BaseClause): + """ a single variable st statement """ + + def __unicode__(self): + return u'"{0}" = %({1})s'.format(self.field, self.context_id) + + def insert_tuple(self): + return self.field, self.context_id + + +class ConditionalClause(BaseClause): + """ A single variable iff statement """ + + def __unicode__(self): + return u'"{0}" = %({1})s'.format(self.field, self.context_id) + + def insert_tuple(self): + return self.field, self.context_id + + +class ContainerUpdateTypeMapMeta(type): + + def __init__(cls, name, bases, dct): + if not hasattr(cls, 'type_map'): + cls.type_map = {} + else: + cls.type_map[cls.col_type] = cls + super(ContainerUpdateTypeMapMeta, cls).__init__(name, bases, dct) + + +class ContainerUpdateClause(AssignmentClause, metaclass=ContainerUpdateTypeMapMeta): + + def __init__(self, field, value, operation=None, previous=None): + super(ContainerUpdateClause, self).__init__(field, value) + self.previous = previous + self._assignments = None + self._operation = operation + self._analyzed = False + + def _analyze(self): + raise NotImplementedError + + def get_context_size(self): + raise NotImplementedError + + def update_context(self, ctx): + raise NotImplementedError + + +class SetUpdateClause(ContainerUpdateClause): + """ updates a set collection """ + + col_type = columns.Set + + _additions = None + _removals = None + + def __unicode__(self): + qs = [] + ctx_id = self.context_id + if (self.previous is None and + self._assignments is None and + self._additions is None and + self._removals is None): + qs += ['"{0}" = %({1})s'.format(self.field, ctx_id)] + if self._assignments is not None: + qs += ['"{0}" = %({1})s'.format(self.field, ctx_id)] + ctx_id += 1 + if self._additions is not None: + qs += ['"{0}" = "{0}" + %({1})s'.format(self.field, ctx_id)] + ctx_id += 1 + if self._removals is not None: + qs += ['"{0}" = "{0}" - %({1})s'.format(self.field, ctx_id)] + + return ', '.join(qs) + + def _analyze(self): + """ works out the updates to be performed """ + if self.value is None or self.value == self.previous: + pass + elif self._operation == "add": + self._additions = self.value + elif self._operation == "remove": + self._removals = self.value + elif self.previous is None: + self._assignments = self.value + else: + # partial update time + self._additions = (self.value - self.previous) or None + self._removals = (self.previous - self.value) or None + self._analyzed = True + + def get_context_size(self): + if not self._analyzed: + self._analyze() + if (self.previous is None and + not self._assignments and + self._additions is None and + self._removals is None): + return 1 + return int(bool(self._assignments)) + int(bool(self._additions)) + int(bool(self._removals)) + + def update_context(self, ctx): + if not self._analyzed: + self._analyze() + ctx_id = self.context_id + if (self.previous is None and + self._assignments is None and + self._additions is None and + self._removals is None): + ctx[str(ctx_id)] = set() + if self._assignments is not None: + ctx[str(ctx_id)] = self._assignments + ctx_id += 1 + if self._additions is not None: + ctx[str(ctx_id)] = self._additions + ctx_id += 1 + if self._removals is not None: + ctx[str(ctx_id)] = self._removals + + +class ListUpdateClause(ContainerUpdateClause): + """ updates a list collection """ + + col_type = columns.List + + _append = None + _prepend = None + + def __unicode__(self): + if not self._analyzed: + self._analyze() + qs = [] + ctx_id = self.context_id + if self._assignments is not None: + qs += ['"{0}" = %({1})s'.format(self.field, ctx_id)] + ctx_id += 1 + + if self._prepend is not None: + qs += ['"{0}" = %({1})s + "{0}"'.format(self.field, ctx_id)] + ctx_id += 1 + + if self._append is not None: + qs += ['"{0}" = "{0}" + %({1})s'.format(self.field, ctx_id)] + + return ', '.join(qs) + + def get_context_size(self): + if not self._analyzed: + self._analyze() + return int(self._assignments is not None) + int(bool(self._append)) + int(bool(self._prepend)) + + def update_context(self, ctx): + if not self._analyzed: + self._analyze() + ctx_id = self.context_id + if self._assignments is not None: + ctx[str(ctx_id)] = self._assignments + ctx_id += 1 + if self._prepend is not None: + ctx[str(ctx_id)] = self._prepend + ctx_id += 1 + if self._append is not None: + ctx[str(ctx_id)] = self._append + + def _analyze(self): + """ works out the updates to be performed """ + if self.value is None or self.value == self.previous: + pass + + elif self._operation == "append": + self._append = self.value + + elif self._operation == "prepend": + self._prepend = self.value + + elif self.previous is None: + self._assignments = self.value + + elif len(self.value) < len(self.previous): + # if elements have been removed, + # rewrite the whole list + self._assignments = self.value + + elif len(self.previous) == 0: + # if we're updating from an empty + # list, do a complete insert + self._assignments = self.value + else: + + # the max start idx we want to compare + search_space = len(self.value) - max(0, len(self.previous) - 1) + + # the size of the sub lists we want to look at + search_size = len(self.previous) + + for i in range(search_space): + # slice boundary + j = i + search_size + sub = self.value[i:j] + idx_cmp = lambda idx: self.previous[idx] == sub[idx] + if idx_cmp(0) and idx_cmp(-1) and self.previous == sub: + self._prepend = self.value[:i] or None + self._append = self.value[j:] or None + break + + # if both append and prepend are still None after looking + # at both lists, an insert statement will be created + if self._prepend is self._append is None: + self._assignments = self.value + + self._analyzed = True + + +class MapUpdateClause(ContainerUpdateClause): + """ updates a map collection """ + + col_type = columns.Map + + _updates = None + _removals = None + + def _analyze(self): + if self._operation == "update": + self._updates = self.value.keys() + elif self._operation == "remove": + self._removals = {v for v in self.value.keys()} + else: + if self.previous is None: + self._updates = sorted([k for k, v in self.value.items()]) + else: + self._updates = sorted([k for k, v in self.value.items() if v != self.previous.get(k)]) or None + self._analyzed = True + + def get_context_size(self): + if self.is_assignment: + return 1 + return int((len(self._updates or []) * 2) + int(bool(self._removals))) + + def update_context(self, ctx): + ctx_id = self.context_id + if self.is_assignment: + ctx[str(ctx_id)] = {} + elif self._removals is not None: + ctx[str(ctx_id)] = self._removals + else: + for key in self._updates or []: + val = self.value.get(key) + ctx[str(ctx_id)] = key + ctx[str(ctx_id + 1)] = val + ctx_id += 2 + + @property + def is_assignment(self): + if not self._analyzed: + self._analyze() + return self.previous is None and not self._updates and not self._removals + + def __unicode__(self): + qs = [] + + ctx_id = self.context_id + if self.is_assignment: + qs += ['"{0}" = %({1})s'.format(self.field, ctx_id)] + elif self._removals is not None: + qs += ['"{0}" = "{0}" - %({1})s'.format(self.field, ctx_id)] + ctx_id += 1 + else: + for _ in self._updates or []: + qs += ['"{0}"[%({1})s] = %({2})s'.format(self.field, ctx_id, ctx_id + 1)] + ctx_id += 2 + + return ', '.join(qs) + + +class CounterUpdateClause(AssignmentClause): + + col_type = columns.Counter + + def __init__(self, field, value, previous=None): + super(CounterUpdateClause, self).__init__(field, value) + self.previous = previous or 0 + + def get_context_size(self): + return 1 + + def update_context(self, ctx): + ctx[str(self.context_id)] = abs(self.value - self.previous) + + def __unicode__(self): + delta = self.value - self.previous + sign = '-' if delta < 0 else '+' + return '"{0}" = "{0}" {1} %({2})s'.format(self.field, sign, self.context_id) + + +class BaseDeleteClause(BaseClause): + pass + + +class FieldDeleteClause(BaseDeleteClause): + """ deletes a field from a row """ + + def __init__(self, field): + super(FieldDeleteClause, self).__init__(field, None) + + def __unicode__(self): + return '"{0}"'.format(self.field) + + def update_context(self, ctx): + pass + + def get_context_size(self): + return 0 + + +class MapDeleteClause(BaseDeleteClause): + """ removes keys from a map """ + + def __init__(self, field, value, previous=None): + super(MapDeleteClause, self).__init__(field, value) + self.value = self.value or {} + self.previous = previous or {} + self._analyzed = False + self._removals = None + + def _analyze(self): + self._removals = sorted([k for k in self.previous if k not in self.value]) + self._analyzed = True + + def update_context(self, ctx): + if not self._analyzed: + self._analyze() + for idx, key in enumerate(self._removals): + ctx[str(self.context_id + idx)] = key + + def get_context_size(self): + if not self._analyzed: + self._analyze() + return len(self._removals) + + def __unicode__(self): + if not self._analyzed: + self._analyze() + return ', '.join(['"{0}"[%({1})s]'.format(self.field, self.context_id + i) for i in range(len(self._removals))]) + + +class BaseCQLStatement(UnicodeMixin): + """ The base cql statement class """ + + def __init__(self, table, timestamp=None, where=None, fetch_size=None, conditionals=None): + super(BaseCQLStatement, self).__init__() + self.table = table + self.context_id = 0 + self.context_counter = self.context_id + self.timestamp = timestamp + self.fetch_size = fetch_size if fetch_size else FETCH_SIZE_UNSET + + self.where_clauses = [] + for clause in where or []: + self._add_where_clause(clause) + + self.conditionals = [] + for conditional in conditionals or []: + self.add_conditional_clause(conditional) + + def _update_part_key_values(self, field_index_map, clauses, parts): + for clause in filter(lambda c: c.field in field_index_map, clauses): + parts[field_index_map[clause.field]] = clause.value + + def partition_key_values(self, field_index_map): + parts = [None] * len(field_index_map) + self._update_part_key_values(field_index_map, (w for w in self.where_clauses if w.operator.__class__ == EqualsOperator), parts) + return parts + + def add_where(self, column, operator, value, quote_field=True): + value = column.to_database(value) + clause = WhereClause(column.db_field_name, operator, value, quote_field) + self._add_where_clause(clause) + + def _add_where_clause(self, clause): + clause.set_context_id(self.context_counter) + self.context_counter += clause.get_context_size() + self.where_clauses.append(clause) + + def get_context(self): + """ + returns the context dict for this statement + :rtype: dict + """ + ctx = {} + for clause in self.where_clauses or []: + clause.update_context(ctx) + return ctx + + def add_conditional_clause(self, clause): + """ + Adds a iff clause to this statement + + :param clause: The clause that will be added to the iff statement + :type clause: ConditionalClause + """ + clause.set_context_id(self.context_counter) + self.context_counter += clause.get_context_size() + self.conditionals.append(clause) + + def _get_conditionals(self): + return 'IF {0}'.format(' AND '.join([str(c) for c in self.conditionals])) + + def get_context_size(self): + return len(self.get_context()) + + def update_context_id(self, i): + self.context_id = i + self.context_counter = self.context_id + for clause in self.where_clauses: + clause.set_context_id(self.context_counter) + self.context_counter += clause.get_context_size() + + @property + def timestamp_normalized(self): + """ + we're expecting self.timestamp to be either a long, int, a datetime, or a timedelta + :return: + """ + if not self.timestamp: + return None + + if isinstance(self.timestamp, int): + return self.timestamp + + if isinstance(self.timestamp, timedelta): + tmp = datetime.now() + self.timestamp + else: + tmp = self.timestamp + + return int(time.mktime(tmp.timetuple()) * 1e+6 + tmp.microsecond) + + def __unicode__(self): + raise NotImplementedError + + def __repr__(self): + return self.__unicode__() + + @property + def _where(self): + return 'WHERE {0}'.format(' AND '.join([str(c) for c in self.where_clauses])) + + +class SelectStatement(BaseCQLStatement): + """ a cql select statement """ + + def __init__(self, + table, + fields=None, + count=False, + where=None, + order_by=None, + limit=None, + allow_filtering=False, + distinct_fields=None, + fetch_size=None): + + """ + :param where + :type where list of cqlengine.statements.WhereClause + """ + super(SelectStatement, self).__init__( + table, + where=where, + fetch_size=fetch_size + ) + + self.fields = [fields] if isinstance(fields, str) else (fields or []) + self.distinct_fields = distinct_fields + self.count = count + self.order_by = [order_by] if isinstance(order_by, str) else order_by + self.limit = limit + self.allow_filtering = allow_filtering + + def __unicode__(self): + qs = ['SELECT'] + if self.distinct_fields: + if self.count: + qs += ['DISTINCT COUNT({0})'.format(', '.join(['"{0}"'.format(f) for f in self.distinct_fields]))] + else: + qs += ['DISTINCT {0}'.format(', '.join(['"{0}"'.format(f) for f in self.distinct_fields]))] + elif self.count: + qs += ['COUNT(*)'] + else: + qs += [', '.join(['"{0}"'.format(f) for f in self.fields]) if self.fields else '*'] + qs += ['FROM', self.table] + + if self.where_clauses: + qs += [self._where] + + if self.order_by and not self.count: + qs += ['ORDER BY {0}'.format(', '.join(str(o) for o in self.order_by))] + + if self.limit: + qs += ['LIMIT {0}'.format(self.limit)] + + if self.allow_filtering: + qs += ['ALLOW FILTERING'] + + return ' '.join(qs) + + +class AssignmentStatement(BaseCQLStatement): + """ value assignment statements """ + + def __init__(self, + table, + assignments=None, + where=None, + ttl=None, + timestamp=None, + conditionals=None): + super(AssignmentStatement, self).__init__( + table, + where=where, + conditionals=conditionals + ) + self.ttl = ttl + self.timestamp = timestamp + + # add assignments + self.assignments = [] + for assignment in assignments or []: + self._add_assignment_clause(assignment) + + def update_context_id(self, i): + super(AssignmentStatement, self).update_context_id(i) + for assignment in self.assignments: + assignment.set_context_id(self.context_counter) + self.context_counter += assignment.get_context_size() + + def partition_key_values(self, field_index_map): + parts = super(AssignmentStatement, self).partition_key_values(field_index_map) + self._update_part_key_values(field_index_map, self.assignments, parts) + return parts + + def add_assignment(self, column, value): + value = column.to_database(value) + clause = AssignmentClause(column.db_field_name, value) + self._add_assignment_clause(clause) + + def _add_assignment_clause(self, clause): + clause.set_context_id(self.context_counter) + self.context_counter += clause.get_context_size() + self.assignments.append(clause) + + @property + def is_empty(self): + return len(self.assignments) == 0 + + def get_context(self): + ctx = super(AssignmentStatement, self).get_context() + for clause in self.assignments: + clause.update_context(ctx) + return ctx + + +class InsertStatement(AssignmentStatement): + """ an cql insert statement """ + + def __init__(self, + table, + assignments=None, + where=None, + ttl=None, + timestamp=None, + if_not_exists=False): + super(InsertStatement, self).__init__(table, + assignments=assignments, + where=where, + ttl=ttl, + timestamp=timestamp) + + self.if_not_exists = if_not_exists + + def __unicode__(self): + qs = ['INSERT INTO {0}'.format(self.table)] + + # get column names and context placeholders + fields = [a.insert_tuple() for a in self.assignments] + columns, values = zip(*fields) + + qs += ["({0})".format(', '.join(['"{0}"'.format(c) for c in columns]))] + qs += ['VALUES'] + qs += ["({0})".format(', '.join(['%({0})s'.format(v) for v in values]))] + + if self.if_not_exists: + qs += ["IF NOT EXISTS"] + + using_options = [] + if self.ttl: + using_options += ["TTL {}".format(self.ttl)] + + if self.timestamp: + using_options += ["TIMESTAMP {}".format(self.timestamp_normalized)] + + if using_options: + qs += ["USING {}".format(" AND ".join(using_options))] + return ' '.join(qs) + + +class UpdateStatement(AssignmentStatement): + """ an cql update select statement """ + + def __init__(self, + table, + assignments=None, + where=None, + ttl=None, + timestamp=None, + conditionals=None, + if_exists=False): + super(UpdateStatement, self). __init__(table, + assignments=assignments, + where=where, + ttl=ttl, + timestamp=timestamp, + conditionals=conditionals) + + self.if_exists = if_exists + + def __unicode__(self): + qs = ['UPDATE', self.table] + + using_options = [] + + if self.ttl: + using_options += ["TTL {0}".format(self.ttl)] + + if self.timestamp: + using_options += ["TIMESTAMP {0}".format(self.timestamp_normalized)] + + if using_options: + qs += ["USING {0}".format(" AND ".join(using_options))] + + qs += ['SET'] + qs += [', '.join([str(c) for c in self.assignments])] + + if self.where_clauses: + qs += [self._where] + + if len(self.conditionals) > 0: + qs += [self._get_conditionals()] + + if self.if_exists: + qs += ["IF EXISTS"] + + return ' '.join(qs) + + def get_context(self): + ctx = super(UpdateStatement, self).get_context() + for clause in self.conditionals: + clause.update_context(ctx) + return ctx + + def update_context_id(self, i): + super(UpdateStatement, self).update_context_id(i) + for conditional in self.conditionals: + conditional.set_context_id(self.context_counter) + self.context_counter += conditional.get_context_size() + + def add_update(self, column, value, operation=None, previous=None): + # For remove all values are None, no need to convert them + if operation != 'remove': + value = column.to_database(value) + col_type = type(column) + container_update_type = ContainerUpdateClause.type_map.get(col_type) + if container_update_type: + previous = column.to_database(previous) + clause = container_update_type(column.db_field_name, value, operation, previous) + elif col_type == columns.Counter: + clause = CounterUpdateClause(column.db_field_name, value, previous) + else: + clause = AssignmentClause(column.db_field_name, value) + if clause.get_context_size(): # this is to exclude map removals from updates. Can go away if we drop support for C* < 1.2.4 and remove two-phase updates + self._add_assignment_clause(clause) + + +class DeleteStatement(BaseCQLStatement): + """ a cql delete statement """ + + def __init__(self, table, fields=None, where=None, timestamp=None, conditionals=None, if_exists=False): + super(DeleteStatement, self).__init__( + table, + where=where, + timestamp=timestamp, + conditionals=conditionals + ) + self.fields = [] + if isinstance(fields, str): + fields = [fields] + for field in fields or []: + self.add_field(field) + + self.if_exists = if_exists + + def update_context_id(self, i): + super(DeleteStatement, self).update_context_id(i) + for field in self.fields: + field.set_context_id(self.context_counter) + self.context_counter += field.get_context_size() + for t in self.conditionals: + t.set_context_id(self.context_counter) + self.context_counter += t.get_context_size() + + def get_context(self): + ctx = super(DeleteStatement, self).get_context() + for field in self.fields: + field.update_context(ctx) + for clause in self.conditionals: + clause.update_context(ctx) + return ctx + + def add_field(self, field): + if isinstance(field, str): + field = FieldDeleteClause(field) + if not isinstance(field, BaseClause): + raise StatementException("only instances of AssignmentClause can be added to statements") + field.set_context_id(self.context_counter) + self.context_counter += field.get_context_size() + self.fields.append(field) + + def __unicode__(self): + qs = ['DELETE'] + if self.fields: + qs += [', '.join(['{0}'.format(f) for f in self.fields])] + qs += ['FROM', self.table] + + delete_option = [] + + if self.timestamp: + delete_option += ["TIMESTAMP {0}".format(self.timestamp_normalized)] + + if delete_option: + qs += [" USING {0} ".format(" AND ".join(delete_option))] + + if self.where_clauses: + qs += [self._where] + + if self.conditionals: + qs += [self._get_conditionals()] + + if self.if_exists: + qs += ["IF EXISTS"] + + return ' '.join(qs) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/usertype.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/usertype.py new file mode 100644 index 0000000000000000000000000000000000000000..7fa85f19199ef10015d9879de62a61497bba5498 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqlengine/usertype.py @@ -0,0 +1,227 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import re + +from cassandra.util import OrderedDict +from cassandra.cqlengine import CQLEngineException +from cassandra.cqlengine import columns +from cassandra.cqlengine import connection as conn +from cassandra.cqlengine import models + + +class UserTypeException(CQLEngineException): + pass + + +class UserTypeDefinitionException(UserTypeException): + pass + + +class BaseUserType(object): + """ + The base type class; don't inherit from this, inherit from UserType, defined below + """ + __type_name__ = None + + _fields = None + _db_map = None + + def __init__(self, **values): + self._values = {} + if self._db_map: + values = dict((self._db_map.get(k, k), v) for k, v in values.items()) + + for name, field in self._fields.items(): + field_default = field.get_default() if field.has_default else None + value = values.get(name, field_default) + if value is not None or isinstance(field, columns.BaseContainerColumn): + value = field.to_python(value) + value_mngr = field.value_manager(self, field, value) + value_mngr.explicit = name in values + self._values[name] = value_mngr + + def __eq__(self, other): + if self.__class__ != other.__class__: + return False + + keys = set(self._fields.keys()) + other_keys = set(other._fields.keys()) + if keys != other_keys: + return False + + for key in other_keys: + if getattr(self, key, None) != getattr(other, key, None): + return False + + return True + + def __ne__(self, other): + return not self.__eq__(other) + + def __str__(self): + return "{{{0}}}".format(', '.join("'{0}': {1}".format(k, getattr(self, k)) for k, v in self._values.items())) + + def has_changed_fields(self): + return any(v.changed for v in self._values.values()) + + def reset_changed_fields(self): + for v in self._values.values(): + v.reset_previous_value() + + def __iter__(self): + for field in self._fields.keys(): + yield field + + def __getattr__(self, attr): + # provides the mapping from db_field to fields + try: + return getattr(self, self._db_map[attr]) + except KeyError: + raise AttributeError(attr) + + def __getitem__(self, key): + if not isinstance(key, str): + raise TypeError + if key not in self._fields.keys(): + raise KeyError + return getattr(self, key) + + def __setitem__(self, key, val): + if not isinstance(key, str): + raise TypeError + if key not in self._fields.keys(): + raise KeyError + return setattr(self, key, val) + + def __len__(self): + try: + return self._len + except: + self._len = len(self._fields.keys()) + return self._len + + def keys(self): + """ Returns a list of column IDs. """ + return [k for k in self] + + def values(self): + """ Returns list of column values. """ + return [self[k] for k in self] + + def items(self): + """ Returns a list of column ID/value tuples. """ + return [(k, self[k]) for k in self] + + @classmethod + def register_for_keyspace(cls, keyspace, connection=None): + conn.register_udt(keyspace, cls.type_name(), cls, connection=connection) + + @classmethod + def type_name(cls): + """ + Returns the type name if it's been defined + otherwise, it creates it from the class name + """ + if cls.__type_name__: + type_name = cls.__type_name__.lower() + else: + camelcase = re.compile(r'([a-z])([A-Z])') + ccase = lambda s: camelcase.sub(lambda v: '{0}_{1}'.format(v.group(1), v.group(2)), s) + + type_name = ccase(cls.__name__) + # trim to less than 48 characters or cassandra will complain + type_name = type_name[-48:] + type_name = type_name.lower() + type_name = re.sub(r'^_+', '', type_name) + cls.__type_name__ = type_name + + return type_name + + def validate(self): + """ + Cleans and validates the field values + """ + for name, field in self._fields.items(): + v = getattr(self, name) + if v is None and not self._values[name].explicit and field.has_default: + v = field.get_default() + val = field.validate(v) + setattr(self, name, val) + + +class UserTypeMetaClass(type): + + def __new__(cls, name, bases, attrs): + field_dict = OrderedDict() + + field_defs = [(k, v) for k, v in attrs.items() if isinstance(v, columns.Column)] + field_defs = sorted(field_defs, key=lambda x: x[1].position) + + def _transform_column(field_name, field_obj): + field_dict[field_name] = field_obj + field_obj.set_column_name(field_name) + attrs[field_name] = models.ColumnDescriptor(field_obj) + + # transform field definitions + for k, v in field_defs: + # don't allow a field with the same name as a built-in attribute or method + if k in BaseUserType.__dict__: + raise UserTypeDefinitionException("field '{0}' conflicts with built-in attribute/method".format(k)) + _transform_column(k, v) + + attrs['_fields'] = field_dict + + db_map = {} + for field_name, field in field_dict.items(): + db_field = field.db_field_name + if db_field != field_name: + if db_field in field_dict: + raise UserTypeDefinitionException("db_field '{0}' for field '{1}' conflicts with another attribute name".format(db_field, field_name)) + db_map[db_field] = field_name + attrs['_db_map'] = db_map + + klass = super(UserTypeMetaClass, cls).__new__(cls, name, bases, attrs) + + return klass + + +class UserType(BaseUserType, metaclass=UserTypeMetaClass): + """ + This class is used to model User Defined Types. To define a type, declare a class inheriting from this, + and assign field types as class attributes: + + .. code-block:: python + + # connect with default keyspace ... + + from cassandra.cqlengine.columns import Text, Integer + from cassandra.cqlengine.usertype import UserType + + class address(UserType): + street = Text() + zipcode = Integer() + + from cassandra.cqlengine import management + management.sync_type(address) + + Please see :ref:`user_types` for a complete example and discussion. + """ + + __type_name__ = None + """ + *Optional.* Sets the name of the CQL type for this type. + + If not specified, the type name will be the name of the class, with it's module name as it's prefix. + """ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/datastax/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/datastax/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2c9ca172f8934625b393103a4674ac699e3cda29 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/datastax/__init__.py @@ -0,0 +1,13 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/datastax/graph/graphson.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/datastax/graph/graphson.py new file mode 100644 index 0000000000000000000000000000000000000000..335c7f7825cb36d7761a368f0da4671f7eef5e49 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/datastax/graph/graphson.py @@ -0,0 +1,1132 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import datetime +import base64 +import uuid +import re +import json +from decimal import Decimal +from collections import OrderedDict +import logging +import itertools +from functools import partial + +import ipaddress + + +from cassandra.cqltypes import cql_types_from_string +from cassandra.metadata import UserType +from cassandra.util import Polygon, Point, LineString, Duration +from cassandra.datastax.graph.types import Vertex, VertexProperty, Edge, Path, T + +__all__ = ['GraphSON1Serializer', 'GraphSON1Deserializer', 'GraphSON1TypeDeserializer', + 'GraphSON2Serializer', 'GraphSON2Deserializer', 'GraphSON2Reader', + 'GraphSON3Serializer', 'GraphSON3Deserializer', 'GraphSON3Reader', + 'to_bigint', 'to_int', 'to_double', 'to_float', 'to_smallint', + 'BooleanTypeIO', 'Int16TypeIO', 'Int32TypeIO', 'DoubleTypeIO', + 'FloatTypeIO', 'UUIDTypeIO', 'BigDecimalTypeIO', 'DurationTypeIO', 'InetTypeIO', + 'InstantTypeIO', 'LocalDateTypeIO', 'LocalTimeTypeIO', 'Int64TypeIO', 'BigIntegerTypeIO', + 'LocalDateTypeIO', 'PolygonTypeIO', 'PointTypeIO', 'LineStringTypeIO', 'BlobTypeIO', + 'GraphSON3Serializer', 'GraphSON3Deserializer', 'UserTypeIO', 'TypeWrapperTypeIO'] + +""" +Supported types: + +DSE Graph GraphSON 2.0 GraphSON 3.0 | Python Driver +------------ | -------------- | -------------- | ------------ +text | string | string | str +boolean | | | bool +bigint | g:Int64 | g:Int64 | long +int | g:Int32 | g:Int32 | int +double | g:Double | g:Double | float +float | g:Float | g:Float | float +uuid | g:UUID | g:UUID | UUID +bigdecimal | gx:BigDecimal | gx:BigDecimal | Decimal +duration | gx:Duration | N/A | timedelta (Classic graph only) +DSE Duration | N/A | dse:Duration | Duration (Core graph only) +inet | gx:InetAddress | gx:InetAddress | str (unicode), IPV4Address/IPV6Address (PY3) +timestamp | gx:Instant | gx:Instant | datetime.datetime +date | gx:LocalDate | gx:LocalDate | datetime.date +time | gx:LocalTime | gx:LocalTime | datetime.time +smallint | gx:Int16 | gx:Int16 | int +varint | gx:BigInteger | gx:BigInteger | long +date | gx:LocalDate | gx:LocalDate | Date +polygon | dse:Polygon | dse:Polygon | Polygon +point | dse:Point | dse:Point | Point +linestring | dse:Linestring | dse:LineString | LineString +blob | dse:Blob | dse:Blob | bytearray, buffer (PY2), memoryview (PY3), bytes (PY3) +blob | gx:ByteBuffer | gx:ByteBuffer | bytearray, buffer (PY2), memoryview (PY3), bytes (PY3) +list | N/A | g:List | list (Core graph only) +map | N/A | g:Map | dict (Core graph only) +set | N/A | g:Set | set or list (Core graph only) + Can return a list due to numerical values returned by Java +tuple | N/A | dse:Tuple | tuple (Core graph only) +udt | N/A | dse:UDT | class or namedtuple (Core graph only) +""" + +MAX_INT32 = 2 ** 32 - 1 +MIN_INT32 = -2 ** 31 + +log = logging.getLogger(__name__) + + +class _GraphSONTypeType(type): + """GraphSONType metaclass, required to create a class property.""" + + @property + def graphson_type(cls): + return "{0}:{1}".format(cls.prefix, cls.graphson_base_type) + + +class GraphSONTypeIO(object, metaclass=_GraphSONTypeType): + """Represent a serializable GraphSON type""" + + prefix = 'g' + graphson_base_type = None + cql_type = None + + @classmethod + def definition(cls, value, writer=None): + return {'cqlType': cls.cql_type} + + @classmethod + def serialize(cls, value, writer=None): + return str(value) + + @classmethod + def deserialize(cls, value, reader=None): + return value + + @classmethod + def get_specialized_serializer(cls, value): + return cls + + +class TextTypeIO(GraphSONTypeIO): + cql_type = 'text' + + +class BooleanTypeIO(GraphSONTypeIO): + graphson_base_type = None + cql_type = 'boolean' + + @classmethod + def serialize(cls, value, writer=None): + return bool(value) + + +class IntegerTypeIO(GraphSONTypeIO): + + @classmethod + def serialize(cls, value, writer=None): + return value + + @classmethod + def get_specialized_serializer(cls, value): + if type(value) is int and (value > MAX_INT32 or value < MIN_INT32): + return Int64TypeIO + + return Int32TypeIO + + +class Int16TypeIO(IntegerTypeIO): + prefix = 'gx' + graphson_base_type = 'Int16' + cql_type = 'smallint' + + +class Int32TypeIO(IntegerTypeIO): + graphson_base_type = 'Int32' + cql_type = 'int' + + +class Int64TypeIO(IntegerTypeIO): + graphson_base_type = 'Int64' + cql_type = 'bigint' + + @classmethod + def deserialize(cls, value, reader=None): + return value + + +class FloatTypeIO(GraphSONTypeIO): + graphson_base_type = 'Float' + cql_type = 'float' + + @classmethod + def serialize(cls, value, writer=None): + return value + + @classmethod + def deserialize(cls, value, reader=None): + return float(value) + + +class DoubleTypeIO(FloatTypeIO): + graphson_base_type = 'Double' + cql_type = 'double' + + +class BigIntegerTypeIO(IntegerTypeIO): + prefix = 'gx' + graphson_base_type = 'BigInteger' + + +class LocalDateTypeIO(GraphSONTypeIO): + FORMAT = '%Y-%m-%d' + + prefix = 'gx' + graphson_base_type = 'LocalDate' + cql_type = 'date' + + @classmethod + def serialize(cls, value, writer=None): + return value.isoformat() + + @classmethod + def deserialize(cls, value, reader=None): + try: + return datetime.datetime.strptime(value, cls.FORMAT).date() + except ValueError: + # negative date + return value + + +class InstantTypeIO(GraphSONTypeIO): + prefix = 'gx' + graphson_base_type = 'Instant' + cql_type = 'timestamp' + + @classmethod + def serialize(cls, value, writer=None): + if isinstance(value, datetime.datetime): + value = datetime.datetime(*value.utctimetuple()[:6]).replace(microsecond=value.microsecond) + else: + value = datetime.datetime.combine(value, datetime.datetime.min.time()) + + return "{0}Z".format(value.isoformat()) + + @classmethod + def deserialize(cls, value, reader=None): + try: + d = datetime.datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%fZ') + except ValueError: + d = datetime.datetime.strptime(value, '%Y-%m-%dT%H:%M:%SZ') + return d + + +class LocalTimeTypeIO(GraphSONTypeIO): + FORMATS = [ + '%H:%M', + '%H:%M:%S', + '%H:%M:%S.%f' + ] + + prefix = 'gx' + graphson_base_type = 'LocalTime' + cql_type = 'time' + + @classmethod + def serialize(cls, value, writer=None): + return value.strftime(cls.FORMATS[2]) + + @classmethod + def deserialize(cls, value, reader=None): + dt = None + for f in cls.FORMATS: + try: + dt = datetime.datetime.strptime(value, f) + break + except ValueError: + continue + + if dt is None: + raise ValueError('Unable to decode LocalTime: {0}'.format(value)) + + return dt.time() + + +class BlobTypeIO(GraphSONTypeIO): + prefix = 'dse' + graphson_base_type = 'Blob' + cql_type = 'blob' + + @classmethod + def serialize(cls, value, writer=None): + value = base64.b64encode(value) + value = value.decode('utf-8') + return value + + @classmethod + def deserialize(cls, value, reader=None): + return bytearray(base64.b64decode(value)) + + +class ByteBufferTypeIO(BlobTypeIO): + prefix = 'gx' + graphson_base_type = 'ByteBuffer' + + +class UUIDTypeIO(GraphSONTypeIO): + graphson_base_type = 'UUID' + cql_type = 'uuid' + + @classmethod + def deserialize(cls, value, reader=None): + return uuid.UUID(value) + + +class BigDecimalTypeIO(GraphSONTypeIO): + prefix = 'gx' + graphson_base_type = 'BigDecimal' + cql_type = 'bigdecimal' + + @classmethod + def deserialize(cls, value, reader=None): + return Decimal(value) + + +class DurationTypeIO(GraphSONTypeIO): + prefix = 'gx' + graphson_base_type = 'Duration' + cql_type = 'duration' + + _duration_regex = re.compile(r""" + ^P((?P\d+)D)? + T((?P\d+)H)? + ((?P\d+)M)? + ((?P[0-9.]+)S)?$ + """, re.VERBOSE) + _duration_format = "P{days}DT{hours}H{minutes}M{seconds}S" + + _seconds_in_minute = 60 + _seconds_in_hour = 60 * _seconds_in_minute + _seconds_in_day = 24 * _seconds_in_hour + + @classmethod + def serialize(cls, value, writer=None): + total_seconds = int(value.total_seconds()) + days, total_seconds = divmod(total_seconds, cls._seconds_in_day) + hours, total_seconds = divmod(total_seconds, cls._seconds_in_hour) + minutes, total_seconds = divmod(total_seconds, cls._seconds_in_minute) + total_seconds += value.microseconds / 1e6 + + return cls._duration_format.format( + days=int(days), hours=int(hours), minutes=int(minutes), seconds=total_seconds + ) + + @classmethod + def deserialize(cls, value, reader=None): + duration = cls._duration_regex.match(value) + if duration is None: + raise ValueError('Invalid duration: {0}'.format(value)) + + duration = {k: float(v) if v is not None else 0 + for k, v in duration.groupdict().items()} + return datetime.timedelta(days=duration['days'], hours=duration['hours'], + minutes=duration['minutes'], seconds=duration['seconds']) + + +class DseDurationTypeIO(GraphSONTypeIO): + prefix = 'dse' + graphson_base_type = 'Duration' + cql_type = 'duration' + + @classmethod + def serialize(cls, value, writer=None): + return { + 'months': value.months, + 'days': value.days, + 'nanos': value.nanoseconds + } + + @classmethod + def deserialize(cls, value, reader=None): + return Duration( + reader.deserialize(value['months']), + reader.deserialize(value['days']), + reader.deserialize(value['nanos']) + ) + + +class TypeWrapperTypeIO(GraphSONTypeIO): + + @classmethod + def definition(cls, value, writer=None): + return {'cqlType': value.type_io.cql_type} + + @classmethod + def serialize(cls, value, writer=None): + return value.type_io.serialize(value.value) + + @classmethod + def deserialize(cls, value, reader=None): + return value.type_io.deserialize(value.value) + + +class PointTypeIO(GraphSONTypeIO): + prefix = 'dse' + graphson_base_type = 'Point' + cql_type = "org.apache.cassandra.db.marshal.PointType" + + @classmethod + def deserialize(cls, value, reader=None): + return Point.from_wkt(value) + + +class LineStringTypeIO(GraphSONTypeIO): + prefix = 'dse' + graphson_base_type = 'LineString' + cql_type = "org.apache.cassandra.db.marshal.LineStringType" + + @classmethod + def deserialize(cls, value, reader=None): + return LineString.from_wkt(value) + + +class PolygonTypeIO(GraphSONTypeIO): + prefix = 'dse' + graphson_base_type = 'Polygon' + cql_type = "org.apache.cassandra.db.marshal.PolygonType" + + @classmethod + def deserialize(cls, value, reader=None): + return Polygon.from_wkt(value) + + +class InetTypeIO(GraphSONTypeIO): + prefix = 'gx' + graphson_base_type = 'InetAddress' + cql_type = 'inet' + + +class VertexTypeIO(GraphSONTypeIO): + graphson_base_type = 'Vertex' + + @classmethod + def deserialize(cls, value, reader=None): + vertex = Vertex(id=reader.deserialize(value["id"]), + label=value["label"] if "label" in value else "vertex", + type='vertex', + properties={}) + # avoid the properties processing in Vertex.__init__ + vertex.properties = reader.deserialize(value.get('properties', {})) + return vertex + + +class VertexPropertyTypeIO(GraphSONTypeIO): + graphson_base_type = 'VertexProperty' + + @classmethod + def deserialize(cls, value, reader=None): + return VertexProperty(label=value['label'], + value=reader.deserialize(value["value"]), + properties=reader.deserialize(value.get('properties', {}))) + + +class EdgeTypeIO(GraphSONTypeIO): + graphson_base_type = 'Edge' + + @classmethod + def deserialize(cls, value, reader=None): + in_vertex = Vertex(id=reader.deserialize(value["inV"]), + label=value['inVLabel'], + type='vertex', + properties={}) + out_vertex = Vertex(id=reader.deserialize(value["outV"]), + label=value['outVLabel'], + type='vertex', + properties={}) + return Edge( + id=reader.deserialize(value["id"]), + label=value["label"] if "label" in value else "vertex", + type='edge', + properties=reader.deserialize(value.get("properties", {})), + inV=in_vertex, + inVLabel=value['inVLabel'], + outV=out_vertex, + outVLabel=value['outVLabel'] + ) + + +class PropertyTypeIO(GraphSONTypeIO): + graphson_base_type = 'Property' + + @classmethod + def deserialize(cls, value, reader=None): + return {value["key"]: reader.deserialize(value["value"])} + + +class PathTypeIO(GraphSONTypeIO): + graphson_base_type = 'Path' + + @classmethod + def deserialize(cls, value, reader=None): + labels = [set(label) for label in reader.deserialize(value['labels'])] + objects = [obj for obj in reader.deserialize(value['objects'])] + p = Path(labels, []) + p.objects = objects # avoid the object processing in Path.__init__ + return p + + +class TraversalMetricsTypeIO(GraphSONTypeIO): + graphson_base_type = 'TraversalMetrics' + + @classmethod + def deserialize(cls, value, reader=None): + return reader.deserialize(value) + + +class MetricsTypeIO(GraphSONTypeIO): + graphson_base_type = 'Metrics' + + @classmethod + def deserialize(cls, value, reader=None): + return reader.deserialize(value) + + +class JsonMapTypeIO(GraphSONTypeIO): + """In GraphSON2, dict are simply serialized as json map""" + + @classmethod + def serialize(cls, value, writer=None): + out = {} + for k, v in value.items(): + out[k] = writer.serialize(v, writer) + + return out + + +class MapTypeIO(GraphSONTypeIO): + """In GraphSON3, dict has its own type""" + + graphson_base_type = 'Map' + cql_type = 'map' + + @classmethod + def definition(cls, value, writer=None): + out = OrderedDict([('cqlType', cls.cql_type)]) + out['definition'] = [] + for k, v in value.items(): + # we just need the first pair to write the def + out['definition'].append(writer.definition(k)) + out['definition'].append(writer.definition(v)) + break + return out + + @classmethod + def serialize(cls, value, writer=None): + out = [] + for k, v in value.items(): + out.append(writer.serialize(k, writer)) + out.append(writer.serialize(v, writer)) + + return out + + @classmethod + def deserialize(cls, value, reader=None): + out = {} + a, b = itertools.tee(value) + for key, val in zip( + itertools.islice(a, 0, None, 2), + itertools.islice(b, 1, None, 2) + ): + out[reader.deserialize(key)] = reader.deserialize(val) + return out + + +class ListTypeIO(GraphSONTypeIO): + """In GraphSON3, list has its own type""" + + graphson_base_type = 'List' + cql_type = 'list' + + @classmethod + def definition(cls, value, writer=None): + out = OrderedDict([('cqlType', cls.cql_type)]) + out['definition'] = [] + if value: + out['definition'].append(writer.definition(value[0])) + return out + + @classmethod + def serialize(cls, value, writer=None): + return [writer.serialize(v, writer) for v in value] + + @classmethod + def deserialize(cls, value, reader=None): + return [reader.deserialize(obj) for obj in value] + + +class SetTypeIO(GraphSONTypeIO): + """In GraphSON3, set has its own type""" + + graphson_base_type = 'Set' + cql_type = 'set' + + @classmethod + def definition(cls, value, writer=None): + out = OrderedDict([('cqlType', cls.cql_type)]) + out['definition'] = [] + for v in value: + # we only take into account the first value for the definition + out['definition'].append(writer.definition(v)) + break + return out + + @classmethod + def serialize(cls, value, writer=None): + return [writer.serialize(v, writer) for v in value] + + @classmethod + def deserialize(cls, value, reader=None): + lst = [reader.deserialize(obj) for obj in value] + + s = set(lst) + if len(s) != len(lst): + log.warning("Coercing g:Set to list due to numerical values returned by Java. " + "See TINKERPOP-1844 for details.") + return lst + + return s + + +class BulkSetTypeIO(GraphSONTypeIO): + graphson_base_type = "BulkSet" + + @classmethod + def deserialize(cls, value, reader=None): + out = [] + + a, b = itertools.tee(value) + for val, bulk in zip( + itertools.islice(a, 0, None, 2), + itertools.islice(b, 1, None, 2) + ): + val = reader.deserialize(val) + bulk = reader.deserialize(bulk) + for n in range(bulk): + out.append(val) + + return out + + +class TupleTypeIO(GraphSONTypeIO): + prefix = 'dse' + graphson_base_type = 'Tuple' + cql_type = 'tuple' + + @classmethod + def definition(cls, value, writer=None): + out = OrderedDict() + out['cqlType'] = cls.cql_type + serializers = [writer.get_serializer(s) for s in value] + out['definition'] = [s.definition(v, writer) for v, s in zip(value, serializers)] + return out + + @classmethod + def serialize(cls, value, writer=None): + out = cls.definition(value, writer) + out['value'] = [writer.serialize(v, writer) for v in value] + return out + + @classmethod + def deserialize(cls, value, reader=None): + return tuple(reader.deserialize(obj) for obj in value['value']) + + +class UserTypeIO(GraphSONTypeIO): + prefix = 'dse' + graphson_base_type = 'UDT' + cql_type = 'udt' + + FROZEN_REMOVAL_REGEX = re.compile(r'frozen<"*([^"]+)"*>') + + @classmethod + def cql_types_from_string(cls, typ): + # sanitizing: remove frozen references and double quotes... + return cql_types_from_string( + re.sub(cls.FROZEN_REMOVAL_REGEX, r'\1', typ) + ) + + @classmethod + def get_udt_definition(cls, value, writer): + user_type_name = writer.user_types[type(value)] + keyspace = writer.context['graph_name'] + return writer.context['cluster'].metadata.keyspaces[keyspace].user_types[user_type_name] + + @classmethod + def is_collection(cls, typ): + return typ in ['list', 'tuple', 'map', 'set'] + + @classmethod + def is_udt(cls, typ, writer): + keyspace = writer.context['graph_name'] + if keyspace in writer.context['cluster'].metadata.keyspaces: + return typ in writer.context['cluster'].metadata.keyspaces[keyspace].user_types + return False + + @classmethod + def field_definition(cls, types, writer, name=None): + """ + Build the udt field definition. This is required when we have a complex udt type. + """ + index = -1 + out = [OrderedDict() if name is None else OrderedDict([('fieldName', name)])] + + while types: + index += 1 + typ = types.pop(0) + if index > 0: + out.append(OrderedDict()) + + if cls.is_udt(typ, writer): + keyspace = writer.context['graph_name'] + udt = writer.context['cluster'].metadata.keyspaces[keyspace].user_types[typ] + out[index].update(cls.definition(udt, writer)) + elif cls.is_collection(typ): + out[index]['cqlType'] = typ + definition = cls.field_definition(types, writer) + out[index]['definition'] = definition if isinstance(definition, list) else [definition] + else: + out[index]['cqlType'] = typ + + return out if len(out) > 1 else out[0] + + @classmethod + def definition(cls, value, writer=None): + udt = value if isinstance(value, UserType) else cls.get_udt_definition(value, writer) + return OrderedDict([ + ('cqlType', cls.cql_type), + ('keyspace', udt.keyspace), + ('name', udt.name), + ('definition', [ + cls.field_definition(cls.cql_types_from_string(typ), writer, name=name) + for name, typ in zip(udt.field_names, udt.field_types)]) + ]) + + @classmethod + def serialize(cls, value, writer=None): + udt = cls.get_udt_definition(value, writer) + out = cls.definition(value, writer) + out['value'] = [] + for name, typ in zip(udt.field_names, udt.field_types): + out['value'].append(writer.serialize(getattr(value, name), writer)) + return out + + @classmethod + def deserialize(cls, value, reader=None): + udt_class = reader.context['cluster']._user_types[value['keyspace']][value['name']] + kwargs = zip( + list(map(lambda v: v['fieldName'], value['definition'])), + [reader.deserialize(v) for v in value['value']] + ) + return udt_class(**dict(kwargs)) + + +class TTypeIO(GraphSONTypeIO): + prefix = 'g' + graphson_base_type = 'T' + + @classmethod + def deserialize(cls, value, reader=None): + return T.name_to_value[value] + + +class _BaseGraphSONSerializer(object): + + _serializers = OrderedDict() + + @classmethod + def register(cls, type, serializer): + cls._serializers[type] = serializer + + @classmethod + def get_type_definitions(cls): + return cls._serializers.copy() + + @classmethod + def get_serializer(cls, value): + """ + Get the serializer for a python object. + + :param value: The python object. + """ + + # The serializer matching logic is as follow: + # 1. Try to find the python type by direct access. + # 2. Try to find the first serializer by class inheritance. + # 3. If no serializer found, return the raw value. + + # Note that when trying to find the serializer by class inheritance, + # the order that serializers are registered is important. The use of + # an OrderedDict is to avoid the difference between executions. + serializer = None + try: + serializer = cls._serializers[type(value)] + except KeyError: + for key, serializer_ in cls._serializers.items(): + if isinstance(value, key): + serializer = serializer_ + break + + if serializer: + # A serializer can have specialized serializers (e.g for Int32 and Int64, so value dependant) + serializer = serializer.get_specialized_serializer(value) + + return serializer + + @classmethod + def serialize(cls, value, writer=None): + """ + Serialize a python object to GraphSON. + + e.g 'P42DT10H5M37S' + e.g. {'key': value} + + :param value: The python object to serialize. + :param writer: A graphson serializer for recursive types (Optional) + """ + serializer = cls.get_serializer(value) + if serializer: + return serializer.serialize(value, writer or cls) + + return value + + +class GraphSON1Serializer(_BaseGraphSONSerializer): + """ + Serialize python objects to graphson types. + """ + + # When we fall back to a superclass's serializer, we iterate over this map. + # We want that iteration order to be consistent, so we use an OrderedDict, + # not a dict. + _serializers = OrderedDict([ + (str, TextTypeIO), + (bool, BooleanTypeIO), + (bytearray, ByteBufferTypeIO), + (Decimal, BigDecimalTypeIO), + (datetime.date, LocalDateTypeIO), + (datetime.time, LocalTimeTypeIO), + (datetime.timedelta, DurationTypeIO), + (datetime.datetime, InstantTypeIO), + (uuid.UUID, UUIDTypeIO), + (Polygon, PolygonTypeIO), + (Point, PointTypeIO), + (LineString, LineStringTypeIO), + (dict, JsonMapTypeIO), + (float, FloatTypeIO) + ]) + + +GraphSON1Serializer.register(ipaddress.IPv4Address, InetTypeIO) +GraphSON1Serializer.register(ipaddress.IPv6Address, InetTypeIO) +GraphSON1Serializer.register(memoryview, ByteBufferTypeIO) +GraphSON1Serializer.register(bytes, ByteBufferTypeIO) + + +class _BaseGraphSONDeserializer(object): + + _deserializers = {} + + @classmethod + def get_type_definitions(cls): + return cls._deserializers.copy() + + @classmethod + def register(cls, graphson_type, serializer): + cls._deserializers[graphson_type] = serializer + + @classmethod + def get_deserializer(cls, graphson_type): + try: + return cls._deserializers[graphson_type] + except KeyError: + raise ValueError('Invalid `graphson_type` specified: {}'.format(graphson_type)) + + @classmethod + def deserialize(cls, graphson_type, value): + """ + Deserialize a `graphson_type` value to a python object. + + :param graphson_base_type: The graphson graphson_type. e.g. 'gx:Instant' + :param value: The graphson value to deserialize. + """ + return cls.get_deserializer(graphson_type).deserialize(value) + + +class GraphSON1Deserializer(_BaseGraphSONDeserializer): + """ + Deserialize graphson1 types to python objects. + """ + _TYPES = [UUIDTypeIO, BigDecimalTypeIO, InstantTypeIO, BlobTypeIO, ByteBufferTypeIO, + PointTypeIO, LineStringTypeIO, PolygonTypeIO, LocalDateTypeIO, + LocalTimeTypeIO, DurationTypeIO, InetTypeIO] + + _deserializers = { + t.graphson_type: t + for t in _TYPES + } + + @classmethod + def deserialize_date(cls, value): + return cls._deserializers[LocalDateTypeIO.graphson_type].deserialize(value) + + @classmethod + def deserialize_time(cls, value): + return cls._deserializers[LocalTimeTypeIO.graphson_type].deserialize(value) + + @classmethod + def deserialize_timestamp(cls, value): + return cls._deserializers[InstantTypeIO.graphson_type].deserialize(value) + + @classmethod + def deserialize_duration(cls, value): + return cls._deserializers[DurationTypeIO.graphson_type].deserialize(value) + + @classmethod + def deserialize_int(cls, value): + return int(value) + + deserialize_smallint = deserialize_int + + deserialize_varint = deserialize_int + + @classmethod + def deserialize_bigint(cls, value): + return cls.deserialize_int(value) + + @classmethod + def deserialize_double(cls, value): + return float(value) + + deserialize_float = deserialize_double + + @classmethod + def deserialize_uuid(cls, value): + return cls._deserializers[UUIDTypeIO.graphson_type].deserialize(value) + + @classmethod + def deserialize_decimal(cls, value): + return cls._deserializers[BigDecimalTypeIO.graphson_type].deserialize(value) + + @classmethod + def deserialize_blob(cls, value): + return cls._deserializers[ByteBufferTypeIO.graphson_type].deserialize(value) + + @classmethod + def deserialize_point(cls, value): + return cls._deserializers[PointTypeIO.graphson_type].deserialize(value) + + @classmethod + def deserialize_linestring(cls, value): + return cls._deserializers[LineStringTypeIO.graphson_type].deserialize(value) + + @classmethod + def deserialize_polygon(cls, value): + return cls._deserializers[PolygonTypeIO.graphson_type].deserialize(value) + + @classmethod + def deserialize_inet(cls, value): + return value + + @classmethod + def deserialize_boolean(cls, value): + return value + + +# TODO Remove in the next major +GraphSON1TypeDeserializer = GraphSON1Deserializer +GraphSON1TypeSerializer = GraphSON1Serializer + + +class GraphSON2Serializer(_BaseGraphSONSerializer): + TYPE_KEY = "@type" + VALUE_KEY = "@value" + + _serializers = GraphSON1Serializer.get_type_definitions() + + def serialize(self, value, writer=None): + """ + Serialize a type to GraphSON2. + + e.g {'@type': 'gx:Duration', '@value': 'P2DT4H'} + + :param value: The python object to serialize. + """ + serializer = self.get_serializer(value) + if not serializer: + raise ValueError("Unable to find a serializer for value of type: ".format(type(value))) + + val = serializer.serialize(value, writer or self) + if serializer is TypeWrapperTypeIO: + graphson_base_type = value.type_io.graphson_base_type + graphson_type = value.type_io.graphson_type + else: + graphson_base_type = serializer.graphson_base_type + graphson_type = serializer.graphson_type + + if graphson_base_type is None: + out = val + else: + out = {self.TYPE_KEY: graphson_type} + if val is not None: + out[self.VALUE_KEY] = val + + return out + + +GraphSON2Serializer.register(int, IntegerTypeIO) + + +class GraphSON2Deserializer(_BaseGraphSONDeserializer): + + _TYPES = GraphSON1Deserializer._TYPES + [ + Int16TypeIO, Int32TypeIO, Int64TypeIO, DoubleTypeIO, FloatTypeIO, + BigIntegerTypeIO, VertexTypeIO, VertexPropertyTypeIO, EdgeTypeIO, + PathTypeIO, PropertyTypeIO, TraversalMetricsTypeIO, MetricsTypeIO] + + _deserializers = { + t.graphson_type: t + for t in _TYPES + } + + +class GraphSON2Reader(object): + """ + GraphSON2 Reader that parse json and deserialize to python objects. + """ + + def __init__(self, context, extra_deserializer_map=None): + """ + :param extra_deserializer_map: map from GraphSON type tag to deserializer instance implementing `deserialize` + """ + self.context = context + self.deserializers = GraphSON2Deserializer.get_type_definitions() + if extra_deserializer_map: + self.deserializers.update(extra_deserializer_map) + + def read(self, json_data): + """ + Read and deserialize ``json_data``. + """ + return self.deserialize(json.loads(json_data)) + + def deserialize(self, obj): + """ + Deserialize GraphSON type-tagged dict values into objects mapped in self.deserializers + """ + if isinstance(obj, dict): + try: + des = self.deserializers[obj[GraphSON2Serializer.TYPE_KEY]] + return des.deserialize(obj[GraphSON2Serializer.VALUE_KEY], self) + except KeyError: + pass + # list and map are treated as normal json objs (could be isolated deserializers) + return {self.deserialize(k): self.deserialize(v) for k, v in obj.items()} + elif isinstance(obj, list): + return [self.deserialize(o) for o in obj] + else: + return obj + + +class TypeIOWrapper(object): + """Used to force a graphson type during serialization""" + + type_io = None + value = None + + def __init__(self, type_io, value): + self.type_io = type_io + self.value = value + + +def _wrap_value(type_io, value): + return TypeIOWrapper(type_io, value) + + +to_bigint = partial(_wrap_value, Int64TypeIO) +to_int = partial(_wrap_value, Int32TypeIO) +to_smallint = partial(_wrap_value, Int16TypeIO) +to_double = partial(_wrap_value, DoubleTypeIO) +to_float = partial(_wrap_value, FloatTypeIO) + + +class GraphSON3Serializer(GraphSON2Serializer): + + _serializers = GraphSON2Serializer.get_type_definitions() + + context = None + """A dict of the serialization context""" + + def __init__(self, context): + self.context = context + self.user_types = None + + def definition(self, value): + serializer = self.get_serializer(value) + return serializer.definition(value, self) + + def get_serializer(self, value): + """Custom get_serializer to support UDT/Tuple""" + + serializer = super(GraphSON3Serializer, self).get_serializer(value) + is_namedtuple_udt = serializer is TupleTypeIO and hasattr(value, '_fields') + if not serializer or is_namedtuple_udt: + # Check if UDT + if self.user_types is None: + try: + user_types = self.context['cluster']._user_types[self.context['graph_name']] + self.user_types = dict(map(reversed, user_types.items())) + except KeyError: + self.user_types = {} + + serializer = UserTypeIO if (is_namedtuple_udt or (type(value) in self.user_types)) else serializer + + return serializer + + +GraphSON3Serializer.register(dict, MapTypeIO) +GraphSON3Serializer.register(list, ListTypeIO) +GraphSON3Serializer.register(set, SetTypeIO) +GraphSON3Serializer.register(tuple, TupleTypeIO) +GraphSON3Serializer.register(Duration, DseDurationTypeIO) +GraphSON3Serializer.register(TypeIOWrapper, TypeWrapperTypeIO) + + +class GraphSON3Deserializer(GraphSON2Deserializer): + _TYPES = GraphSON2Deserializer._TYPES + [MapTypeIO, ListTypeIO, + SetTypeIO, TupleTypeIO, + UserTypeIO, DseDurationTypeIO, + TTypeIO, BulkSetTypeIO] + + _deserializers = {t.graphson_type: t for t in _TYPES} + + +class GraphSON3Reader(GraphSON2Reader): + """ + GraphSON3 Reader that parse json and deserialize to python objects. + """ + + def __init__(self, context, extra_deserializer_map=None): + """ + :param context: A dict of the context, mostly used as context for udt deserialization. + :param extra_deserializer_map: map from GraphSON type tag to deserializer instance implementing `deserialize` + """ + self.context = context + self.deserializers = GraphSON3Deserializer.get_type_definitions() + if extra_deserializer_map: + self.deserializers.update(extra_deserializer_map) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/datastax/graph/query.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/datastax/graph/query.py new file mode 100644 index 0000000000000000000000000000000000000000..866df7a94c2430bee6d2cb67c96db05a58521729 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/datastax/graph/query.py @@ -0,0 +1,330 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +from warnings import warn + +from cassandra import ConsistencyLevel +from cassandra.query import Statement, SimpleStatement +from cassandra.datastax.graph.types import Vertex, Edge, Path, VertexProperty +from cassandra.datastax.graph.graphson import GraphSON2Reader, GraphSON3Reader + + +__all__ = [ + 'GraphProtocol', 'GraphOptions', 'GraphStatement', 'SimpleGraphStatement', + 'single_object_row_factory', 'graph_result_row_factory', 'graph_object_row_factory', + 'graph_graphson2_row_factory', 'Result', 'graph_graphson3_row_factory' +] + +# (attr, description, server option) +_graph_options = ( + ('graph_name', 'name of the targeted graph.', 'graph-name'), + ('graph_source', 'choose the graph traversal source, configured on the server side.', 'graph-source'), + ('graph_language', 'the language used in the queries (default "gremlin-groovy")', 'graph-language'), + ('graph_protocol', 'the graph protocol that the server should use for query results (default "graphson-1-0")', 'graph-results'), + ('graph_read_consistency_level', '''read `cassandra.ConsistencyLevel `_ for graph queries (if distinct from session default). +Setting this overrides the native `Statement.consistency_level `_ for read operations from Cassandra persistence''', 'graph-read-consistency'), + ('graph_write_consistency_level', '''write `cassandra.ConsistencyLevel `_ for graph queries (if distinct from session default). +Setting this overrides the native `Statement.consistency_level `_ for write operations to Cassandra persistence.''', 'graph-write-consistency') +) +_graph_option_names = tuple(option[0] for option in _graph_options) + +# this is defined by the execution profile attribute, not in graph options +_request_timeout_key = 'request-timeout' + + +class GraphProtocol(object): + + GRAPHSON_1_0 = b'graphson-1.0' + """ + GraphSON1 + """ + + GRAPHSON_2_0 = b'graphson-2.0' + """ + GraphSON2 + """ + + GRAPHSON_3_0 = b'graphson-3.0' + """ + GraphSON3 + """ + + +class GraphOptions(object): + """ + Options for DSE Graph Query handler. + """ + # See _graph_options map above for notes on valid options + + DEFAULT_GRAPH_PROTOCOL = GraphProtocol.GRAPHSON_1_0 + DEFAULT_GRAPH_LANGUAGE = b'gremlin-groovy' + + def __init__(self, **kwargs): + self._graph_options = {} + kwargs.setdefault('graph_source', 'g') + kwargs.setdefault('graph_language', GraphOptions.DEFAULT_GRAPH_LANGUAGE) + for attr, value in kwargs.items(): + if attr not in _graph_option_names: + warn("Unknown keyword argument received for GraphOptions: {0}".format(attr)) + setattr(self, attr, value) + + def copy(self): + new_options = GraphOptions() + new_options._graph_options = self._graph_options.copy() + return new_options + + def update(self, options): + self._graph_options.update(options._graph_options) + + def get_options_map(self, other_options=None): + """ + Returns a map for these options updated with other options, + and mapped to graph payload types. + """ + options = self._graph_options.copy() + if other_options: + options.update(other_options._graph_options) + + # cls are special-cased so they can be enums in the API, and names in the protocol + for cl in ('graph-write-consistency', 'graph-read-consistency'): + cl_enum = options.get(cl) + if cl_enum is not None: + options[cl] = ConsistencyLevel.value_to_name[cl_enum].encode() + return options + + def set_source_default(self): + """ + Sets ``graph_source`` to the server-defined default traversal source ('default') + """ + self.graph_source = 'default' + + def set_source_analytics(self): + """ + Sets ``graph_source`` to the server-defined analytic traversal source ('a') + """ + self.graph_source = 'a' + + def set_source_graph(self): + """ + Sets ``graph_source`` to the server-defined graph traversal source ('g') + """ + self.graph_source = 'g' + + def set_graph_protocol(self, protocol): + """ + Sets ``graph_protocol`` as server graph results format (See :class:`cassandra.datastax.graph.GraphProtocol`) + """ + self.graph_protocol = protocol + + @property + def is_default_source(self): + return self.graph_source in (b'default', None) + + @property + def is_analytics_source(self): + """ + True if ``graph_source`` is set to the server-defined analytics traversal source ('a') + """ + return self.graph_source == b'a' + + @property + def is_graph_source(self): + """ + True if ``graph_source`` is set to the server-defined graph traversal source ('g') + """ + return self.graph_source == b'g' + + +for opt in _graph_options: + + def get(self, key=opt[2]): + return self._graph_options.get(key) + + def set(self, value, key=opt[2]): + if value is not None: + # normalize text here so it doesn't have to be done every time we get options map + if isinstance(value, str): + value = value.encode() + self._graph_options[key] = value + else: + self._graph_options.pop(key, None) + + def delete(self, key=opt[2]): + self._graph_options.pop(key, None) + + setattr(GraphOptions, opt[0], property(get, set, delete, opt[1])) + + +class GraphStatement(Statement): + """ An abstract class representing a graph query.""" + + @property + def query(self): + raise NotImplementedError() + + def __str__(self): + return u''.format(self.query) + __repr__ = __str__ + + +class SimpleGraphStatement(GraphStatement, SimpleStatement): + """ + Simple graph statement for :meth:`.Session.execute_graph`. + Takes the same parameters as :class:`.SimpleStatement`. + """ + @property + def query(self): + return self._query_string + + +def single_object_row_factory(column_names, rows): + """ + returns the JSON string value of graph results + """ + return [row[0] for row in rows] + + +def graph_result_row_factory(column_names, rows): + """ + Returns a :class:`Result ` object that can load graph results and produce specific types. + The Result JSON is deserialized and unpacked from the top-level 'result' dict. + """ + return [Result(json.loads(row[0])['result']) for row in rows] + + +def graph_object_row_factory(column_names, rows): + """ + Like :func:`~.graph_result_row_factory`, except known element types (:class:`~.Vertex`, :class:`~.Edge`) are + converted to their simplified objects. Some low-level metadata is shed in this conversion. Unknown result types are + still returned as :class:`Result `. + """ + return _graph_object_sequence(json.loads(row[0])['result'] for row in rows) + + +def _graph_object_sequence(objects): + for o in objects: + res = Result(o) + if isinstance(o, dict): + typ = res.value.get('type') + if typ == 'vertex': + res = res.as_vertex() + elif typ == 'edge': + res = res.as_edge() + yield res + + +class _GraphSONContextRowFactory(object): + graphson_reader_class = None + graphson_reader_kwargs = None + + def __init__(self, cluster): + context = {'cluster': cluster} + kwargs = self.graphson_reader_kwargs or {} + self.graphson_reader = self.graphson_reader_class(context, **kwargs) + + def __call__(self, column_names, rows): + return [self.graphson_reader.read(row[0])['result'] for row in rows] + + +class _GraphSON2RowFactory(_GraphSONContextRowFactory): + """Row factory to deserialize GraphSON2 results.""" + graphson_reader_class = GraphSON2Reader + + +class _GraphSON3RowFactory(_GraphSONContextRowFactory): + """Row factory to deserialize GraphSON3 results.""" + graphson_reader_class = GraphSON3Reader + + +graph_graphson2_row_factory = _GraphSON2RowFactory +graph_graphson3_row_factory = _GraphSON3RowFactory + + +class Result(object): + """ + Represents deserialized graph results. + Property and item getters are provided for convenience. + """ + + value = None + """ + Deserialized value from the result + """ + + def __init__(self, value): + self.value = value + + def __getattr__(self, attr): + if not isinstance(self.value, dict): + raise ValueError("Value cannot be accessed as a dict") + + if attr in self.value: + return self.value[attr] + + raise AttributeError("Result has no top-level attribute %r" % (attr,)) + + def __getitem__(self, item): + if isinstance(self.value, dict) and isinstance(item, str): + return self.value[item] + elif isinstance(self.value, list) and isinstance(item, int): + return self.value[item] + else: + raise ValueError("Result cannot be indexed by %r" % (item,)) + + def __str__(self): + return str(self.value) + + def __repr__(self): + return "%s(%r)" % (Result.__name__, self.value) + + def __eq__(self, other): + return self.value == other.value + + def as_vertex(self): + """ + Return a :class:`Vertex` parsed from this result + + Raises TypeError if parsing fails (i.e. the result structure is not valid). + """ + try: + return Vertex(self.id, self.label, self.type, self.value.get('properties', {})) + except (AttributeError, ValueError, TypeError): + raise TypeError("Could not create Vertex from %r" % (self,)) + + def as_edge(self): + """ + Return a :class:`Edge` parsed from this result + + Raises TypeError if parsing fails (i.e. the result structure is not valid). + """ + try: + return Edge(self.id, self.label, self.type, self.value.get('properties', {}), + self.inV, self.inVLabel, self.outV, self.outVLabel) + except (AttributeError, ValueError, TypeError): + raise TypeError("Could not create Edge from %r" % (self,)) + + def as_path(self): + """ + Return a :class:`Path` parsed from this result + + Raises TypeError if parsing fails (i.e. the result structure is not valid). + """ + try: + return Path(self.labels, self.objects) + except (AttributeError, ValueError, TypeError): + raise TypeError("Could not create Path from %r" % (self,)) + + def as_vertex_property(self): + return VertexProperty(self.value.get('label'), self.value.get('value'), self.value.get('properties', {})) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/datastax/graph/types.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/datastax/graph/types.py new file mode 100644 index 0000000000000000000000000000000000000000..9817c99d7dab67e933e664e8d58618249f883808 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/datastax/graph/types.py @@ -0,0 +1,210 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +__all__ = ['Element', 'Vertex', 'Edge', 'VertexProperty', 'Path', 'T'] + + +class Element(object): + + element_type = None + + _attrs = ('id', 'label', 'type', 'properties') + + def __init__(self, id, label, type, properties): + if type != self.element_type: + raise TypeError("Attempted to create %s from %s element", (type, self.element_type)) + + self.id = id + self.label = label + self.type = type + self.properties = self._extract_properties(properties) + + @staticmethod + def _extract_properties(properties): + return dict(properties) + + def __eq__(self, other): + return all(getattr(self, attr) == getattr(other, attr) for attr in self._attrs) + + def __str__(self): + return str(dict((k, getattr(self, k)) for k in self._attrs)) + + +class Vertex(Element): + """ + Represents a Vertex element from a graph query. + + Vertex ``properties`` are extracted into a ``dict`` of property names to list of :class:`~VertexProperty` (list + because they are always encoded that way, and sometimes have multiple cardinality; VertexProperty because sometimes + the properties themselves have property maps). + """ + + element_type = 'vertex' + + @staticmethod + def _extract_properties(properties): + # vertex properties are always encoded as a list, regardless of Cardinality + return dict((k, [VertexProperty(k, p['value'], p.get('properties')) for p in v]) for k, v in properties.items()) + + def __repr__(self): + properties = dict((name, [{'label': prop.label, 'value': prop.value, 'properties': prop.properties} for prop in prop_list]) + for name, prop_list in self.properties.items()) + return "%s(%r, %r, %r, %r)" % (self.__class__.__name__, + self.id, self.label, + self.type, properties) + + +class VertexProperty(object): + """ + Vertex properties have a top-level value and an optional ``dict`` of properties. + """ + + label = None + """ + label of the property + """ + + value = None + """ + Value of the property + """ + + properties = None + """ + dict of properties attached to the property + """ + + def __init__(self, label, value, properties=None): + self.label = label + self.value = value + self.properties = properties or {} + + def __eq__(self, other): + return isinstance(other, VertexProperty) and self.label == other.label and self.value == other.value and self.properties == other.properties + + def __repr__(self): + return "%s(%r, %r, %r)" % (self.__class__.__name__, self.label, self.value, self.properties) + + +class Edge(Element): + """ + Represents an Edge element from a graph query. + + Attributes match initializer parameters. + """ + + element_type = 'edge' + + _attrs = Element._attrs + ('inV', 'inVLabel', 'outV', 'outVLabel') + + def __init__(self, id, label, type, properties, + inV, inVLabel, outV, outVLabel): + super(Edge, self).__init__(id, label, type, properties) + self.inV = inV + self.inVLabel = inVLabel + self.outV = outV + self.outVLabel = outVLabel + + def __repr__(self): + return "%s(%r, %r, %r, %r, %r, %r, %r, %r)" %\ + (self.__class__.__name__, + self.id, self.label, + self.type, self.properties, + self.inV, self.inVLabel, + self.outV, self.outVLabel) + + +class Path(object): + """ + Represents a graph path. + + Labels list is taken verbatim from the results. + + Objects are either :class:`~.Result` or :class:`~.Vertex`/:class:`~.Edge` for recognized types + """ + + labels = None + """ + List of labels in the path + """ + + objects = None + """ + List of objects in the path + """ + + def __init__(self, labels, objects): + # TODO fix next major + # The Path class should not do any deserialization by itself. To fix in the next major. + from cassandra.datastax.graph.query import _graph_object_sequence + self.labels = labels + self.objects = list(_graph_object_sequence(objects)) + + def __eq__(self, other): + return self.labels == other.labels and self.objects == other.objects + + def __str__(self): + return str({'labels': self.labels, 'objects': self.objects}) + + def __repr__(self): + return "%s(%r, %r)" % (self.__class__.__name__, self.labels, [o.value for o in self.objects]) + + +class T(object): + """ + Represents a collection of tokens for more concise Traversal definitions. + """ + + name = None + val = None + + # class attributes + id = None + """ + """ + + key = None + """ + """ + label = None + """ + """ + value = None + """ + """ + + def __init__(self, name, val): + self.name = name + self.val = val + + def __str__(self): + return self.name + + def __repr__(self): + return "T.%s" % (self.name, ) + + +T.id = T("id", 1) +T.id_ = T("id_", 2) +T.key = T("key", 3) +T.label = T("label", 4) +T.value = T("value", 5) + +T.name_to_value = { + 'id': T.id, + 'id_': T.id_, + 'key': T.key, + 'label': T.label, + 'value': T.value +} diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/graph/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/graph/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..51bd1de16a532c92b073f162bf2b374a41d6b5e1 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/graph/__init__.py @@ -0,0 +1,16 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This is only for backward compatibility when migrating from dse-driver. +from cassandra.datastax.graph import * \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/graph/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/graph/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4e9093793841f71acf7a241e5f8446bbf134493 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/graph/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/graph/__pycache__/graphson.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/graph/__pycache__/graphson.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01961b34a2cae9c9d1726b500503cec6a228757e Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/graph/__pycache__/graphson.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/graph/__pycache__/query.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/graph/__pycache__/query.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20b42c6a3ed9627cf9a8a82ba4b4cf3c03054687 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/graph/__pycache__/query.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/graph/__pycache__/types.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/graph/__pycache__/types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36258bd83871659121359ae6a8410092b908efd3 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/graph/__pycache__/types.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/graph/graphson.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/graph/graphson.py new file mode 100644 index 0000000000000000000000000000000000000000..d37c172a6b812a6442049305f79e721fc8dce360 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/graph/graphson.py @@ -0,0 +1,16 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This is only for backward compatibility when migrating from dse-driver. +from cassandra.datastax.graph.graphson import * diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/graph/query.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/graph/query.py new file mode 100644 index 0000000000000000000000000000000000000000..50eef72ad04414abb761daf4da7da7152b86c9bb --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/graph/query.py @@ -0,0 +1,16 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This is only for backward compatibility when migrating from dse-driver. +from cassandra.datastax.graph.query import * diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/graph/types.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/graph/types.py new file mode 100644 index 0000000000000000000000000000000000000000..c8b613f8e46399f07dfac6ca2d12770bb8c9d529 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/graph/types.py @@ -0,0 +1,16 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This is only for backward compatibility when migrating from dse-driver. +from cassandra.datastax.graph.types import * diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..386372eb4a3d78e7f0b43ea508c4ebe590825b7b --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/__init__.py @@ -0,0 +1,14 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/asyncioreactor.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/asyncioreactor.py new file mode 100644 index 0000000000000000000000000000000000000000..41b744602d5f9d52f5d26b2737b96ce5bd9a3a69 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/asyncioreactor.py @@ -0,0 +1,236 @@ +import threading + +from cassandra.connection import Connection, ConnectionShutdown +import sys +import asyncio +import logging +import os +import socket +import ssl +from threading import Lock, Thread, get_ident + + +log = logging.getLogger(__name__) + + +# This module uses ``yield from`` and ``@asyncio.coroutine`` over ``await`` and +# ``async def`` for pre-Python-3.5 compatibility, so keep in mind that the +# managed coroutines are generator-based, not native coroutines. See PEP 492: +# https://www.python.org/dev/peps/pep-0492/#coroutine-objects + + +try: + asyncio.run_coroutine_threadsafe +except AttributeError: + raise ImportError( + 'Cannot use asyncioreactor without access to ' + 'asyncio.run_coroutine_threadsafe (added in 3.4.6 and 3.5.1)' + ) + + +class AsyncioTimer(object): + """ + An ``asyncioreactor``-specific Timer. Similar to :class:`.connection.Timer, + but with a slightly different API due to limitations in the underlying + ``call_later`` interface. Not meant to be used with a + :class:`.connection.TimerManager`. + """ + + @property + def end(self): + raise NotImplementedError('{} is not compatible with TimerManager and ' + 'does not implement .end()') + + def __init__(self, timeout, callback, loop): + delayed = self._call_delayed_coro(timeout=timeout, + callback=callback) + self._handle = asyncio.run_coroutine_threadsafe(delayed, loop=loop) + + @staticmethod + async def _call_delayed_coro(timeout, callback): + await asyncio.sleep(timeout) + return callback() + + def __lt__(self, other): + try: + return self._handle < other._handle + except AttributeError: + raise NotImplemented + + def cancel(self): + self._handle.cancel() + + def finish(self): + # connection.Timer method not implemented here because we can't inspect + # the Handle returned from call_later + raise NotImplementedError('{} is not compatible with TimerManager and ' + 'does not implement .finish()') + + +class AsyncioConnection(Connection): + """ + An experimental implementation of :class:`.Connection` that uses the + ``asyncio`` module in the Python standard library for its event loop. + + Note that it requires ``asyncio`` features that were only introduced in the + 3.4 line in 3.4.6, and in the 3.5 line in 3.5.1. + """ + + _loop = None + _pid = os.getpid() + + _lock = Lock() + _loop_thread = None + + _write_queue = None + _write_queue_lock = None + + def __init__(self, *args, **kwargs): + Connection.__init__(self, *args, **kwargs) + self._background_tasks = set() + + self._connect_socket() + self._socket.setblocking(0) + loop_args = dict() + if sys.version_info[0] == 3 and sys.version_info[1] < 10: + loop_args['loop'] = self._loop + self._write_queue = asyncio.Queue(**loop_args) + self._write_queue_lock = asyncio.Lock(**loop_args) + + # see initialize_reactor -- loop is running in a separate thread, so we + # have to use a threadsafe call + self._read_watcher = asyncio.run_coroutine_threadsafe( + self.handle_read(), loop=self._loop + ) + self._write_watcher = asyncio.run_coroutine_threadsafe( + self.handle_write(), loop=self._loop + ) + self._send_options_message() + + + + @classmethod + def initialize_reactor(cls): + with cls._lock: + if cls._pid != os.getpid(): + # This means that class was passed to another process, + # e.g. using multiprocessing. + # In such case the class instance will be different and passing + # tasks to loop thread won't work. + # To fix we need to re-initialize the class + cls._loop = None + cls._loop_thread = None + cls._pid = os.getpid() + if cls._loop is None: + assert cls._loop_thread is None + cls._loop = asyncio.new_event_loop() + # daemonize so the loop will be shut down on interpreter + # shutdown + cls._loop_thread = Thread(target=cls._loop.run_forever, + daemon=True, name="asyncio_thread") + cls._loop_thread.start() + + @classmethod + def create_timer(cls, timeout, callback): + return AsyncioTimer(timeout, callback, loop=cls._loop) + + def close(self): + with self.lock: + if self.is_closed: + return + self.is_closed = True + + # close from the loop thread to avoid races when removing file + # descriptors + asyncio.run_coroutine_threadsafe( + self._close(), loop=self._loop + ) + + async def _close(self): + log.debug("Closing connection (%s) to %s" % (id(self), self.endpoint)) + if self._write_watcher: + self._write_watcher.cancel() + if self._read_watcher: + self._read_watcher.cancel() + if self._socket: + self._loop.remove_writer(self._socket.fileno()) + self._loop.remove_reader(self._socket.fileno()) + self._socket.close() + + log.debug("Closed socket to %s" % (self.endpoint,)) + + if not self.is_defunct: + self.error_all_requests( + ConnectionShutdown("Connection to %s was closed" % self.endpoint)) + # don't leave in-progress operations hanging + self.connected_event.set() + + def push(self, data): + buff_size = self.out_buffer_size + if len(data) > buff_size: + chunks = [] + for i in range(0, len(data), buff_size): + chunks.append(data[i:i + buff_size]) + else: + chunks = [data] + + if self._loop_thread != threading.current_thread(): + asyncio.run_coroutine_threadsafe( + self._push_msg(chunks), + loop=self._loop + ) + else: + # avoid races/hangs by just scheduling this, not using threadsafe + task = self._loop.create_task(self._push_msg(chunks)) + + self._background_tasks.add(task) + task.add_done_callback(self._background_tasks.discard) + + async def _push_msg(self, chunks): + # This lock ensures all chunks of a message are sequential in the Queue + async with self._write_queue_lock: + for chunk in chunks: + self._write_queue.put_nowait(chunk) + + + async def handle_write(self): + while True: + try: + next_msg = await self._write_queue.get() + if next_msg: + await self._loop.sock_sendall(self._socket, next_msg) + except socket.error as err: + log.debug("Exception in send for %s: %s", self, err) + self.defunct(err) + return + except asyncio.CancelledError: + return + + async def handle_read(self): + while True: + try: + buf = await self._loop.sock_recv(self._socket, self.in_buffer_size) + self._iobuf.write(buf) + # sock_recv expects EWOULDBLOCK if socket provides no data, but + # nonblocking ssl sockets raise these instead, so we handle them + # ourselves by yielding to the event loop, where the socket will + # get the reading/writing it "wants" before retrying + except (ssl.SSLWantWriteError, ssl.SSLWantReadError): + # Apparently the preferred way to yield to the event loop from within + # a native coroutine based on https://github.com/python/asyncio/issues/284 + await asyncio.sleep(0) + continue + except socket.error as err: + log.debug("Exception during socket recv for %s: %s", + self, err) + self.defunct(err) + return # leave the read loop + except asyncio.CancelledError: + return + + if buf and self._iobuf.tell(): + self.process_io_buffer() + else: + log.debug("Connection %s closed by server", self) + self.close() + return diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/asyncorereactor.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/asyncorereactor.py new file mode 100644 index 0000000000000000000000000000000000000000..2c75e7139d9bd18a439180c8e26c2781369e1f48 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/asyncorereactor.py @@ -0,0 +1,477 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import atexit +from collections import deque +from functools import partial +import logging +import os +import socket +import sys +from threading import Lock, Thread, Event +import time +import weakref +import sys +import ssl + +try: + from weakref import WeakSet +except ImportError: + from cassandra.util import WeakSet # noqa + +from cassandra import DependencyException +try: + import asyncore +except ModuleNotFoundError: + raise DependencyException( + "Unable to import asyncore module. Note that this module has been removed in Python 3.12 " + "so when using the driver with this version (or anything newer) you will need to use one of the " + "other event loop implementations." + ) + +from cassandra.connection import Connection, ConnectionShutdown, NONBLOCKING, Timer, TimerManager + + + +log = logging.getLogger(__name__) + +_dispatcher_map = {} + +def _cleanup(loop): + if loop: + loop._cleanup() + + +class WaitableTimer(Timer): + def __init__(self, timeout, callback): + Timer.__init__(self, timeout, callback) + self.callback = callback + self.event = Event() + + self.final_exception = None + + def finish(self, time_now): + try: + finished = Timer.finish(self, time_now) + if finished: + self.event.set() + return True + return False + + except Exception as e: + self.final_exception = e + self.event.set() + return True + + def wait(self, timeout=None): + self.event.wait(timeout) + if self.final_exception: + raise self.final_exception + + +class _PipeWrapper(object): + + def __init__(self, fd): + self.fd = fd + + def fileno(self): + return self.fd + + def close(self): + os.close(self.fd) + + def getsockopt(self, level, optname, buflen=None): + # act like an unerrored socket for the asyncore error handling + if level == socket.SOL_SOCKET and optname == socket.SO_ERROR and not buflen: + return 0 + raise NotImplementedError() + + +class _AsyncoreDispatcher(asyncore.dispatcher): + + def __init__(self, socket): + asyncore.dispatcher.__init__(self, map=_dispatcher_map) + # inject after to avoid base class validation + self.set_socket(socket) + self._notified = False + + def writable(self): + return False + + def validate(self): + assert not self._notified + self.notify_loop() + assert self._notified + self.loop(0.1) + assert not self._notified + + def loop(self, timeout): + asyncore.loop(timeout=timeout, use_poll=True, map=_dispatcher_map, count=1) + + +class _AsyncorePipeDispatcher(_AsyncoreDispatcher): + + def __init__(self): + self.read_fd, self.write_fd = os.pipe() + _AsyncoreDispatcher.__init__(self, _PipeWrapper(self.read_fd)) + + def writable(self): + return False + + def handle_read(self): + while len(os.read(self.read_fd, 4096)) == 4096: + pass + self._notified = False + + def notify_loop(self): + if not self._notified: + self._notified = True + os.write(self.write_fd, b'x') + + +class _AsyncoreUDPDispatcher(_AsyncoreDispatcher): + """ + Experimental alternate dispatcher for avoiding busy wait in the asyncore loop. It is not used by default because + it relies on local port binding. + Port scanning is not implemented, so multiple clients on one host will collide. This address would need to be set per + instance, or this could be specialized to scan until an address is found. + + To use:: + + from cassandra.io.asyncorereactor import _AsyncoreUDPDispatcher, AsyncoreLoop + AsyncoreLoop._loop_dispatch_class = _AsyncoreUDPDispatcher + + """ + bind_address = ('localhost', 10000) + + def __init__(self): + self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + self._socket.bind(self.bind_address) + self._socket.setblocking(0) + _AsyncoreDispatcher.__init__(self, self._socket) + + def handle_read(self): + try: + d = self._socket.recvfrom(1) + while d and d[1]: + d = self._socket.recvfrom(1) + except socket.error as e: + pass + self._notified = False + + def notify_loop(self): + if not self._notified: + self._notified = True + self._socket.sendto(b'', self.bind_address) + + def loop(self, timeout): + asyncore.loop(timeout=timeout, use_poll=False, map=_dispatcher_map, count=1) + + +class _BusyWaitDispatcher(object): + + max_write_latency = 0.001 + """ + Timeout pushed down to asyncore select/poll. Dictates the amount of time it will sleep before coming back to check + if anything is writable. + """ + + def notify_loop(self): + pass + + def loop(self, timeout): + if not _dispatcher_map: + time.sleep(0.005) + count = timeout // self.max_write_latency + asyncore.loop(timeout=self.max_write_latency, use_poll=True, map=_dispatcher_map, count=count) + + def validate(self): + pass + + def close(self): + pass + + +class AsyncoreLoop(object): + + timer_resolution = 0.1 # used as the max interval to be in the io loop before returning to service timeouts + + _loop_dispatch_class = _AsyncorePipeDispatcher if os.name != 'nt' else _BusyWaitDispatcher + + def __init__(self): + self._pid = os.getpid() + self._loop_lock = Lock() + self._started = False + self._shutdown = False + + self._thread = None + + self._timers = TimerManager() + + try: + dispatcher = self._loop_dispatch_class() + dispatcher.validate() + log.debug("Validated loop dispatch with %s", self._loop_dispatch_class) + except Exception: + log.exception("Failed validating loop dispatch with %s. Using busy wait execution instead.", self._loop_dispatch_class) + dispatcher.close() + dispatcher = _BusyWaitDispatcher() + self._loop_dispatcher = dispatcher + + def maybe_start(self): + should_start = False + did_acquire = False + try: + did_acquire = self._loop_lock.acquire(False) + if did_acquire and not self._started: + self._started = True + should_start = True + finally: + if did_acquire: + self._loop_lock.release() + + if should_start: + self._thread = Thread(target=self._run_loop, name="asyncore_cassandra_driver_event_loop") + self._thread.daemon = True + self._thread.start() + + def wake_loop(self): + self._loop_dispatcher.notify_loop() + + def _run_loop(self): + log.debug("Starting asyncore event loop") + with self._loop_lock: + while not self._shutdown: + try: + self._loop_dispatcher.loop(self.timer_resolution) + self._timers.service_timeouts() + except Exception as exc: + self._maybe_log_debug("Asyncore event loop stopped unexpectedly", exc_info=exc) + break + self._started = False + + self._maybe_log_debug("Asyncore event loop ended") + + def _maybe_log_debug(self, *args, **kwargs): + try: + log.debug(*args, **kwargs) + except Exception: + # TODO: Remove when Python 2 support is removed + # PYTHON-1266. If our logger has disappeared, there's nothing we + # can do, so just log nothing. + pass + + def add_timer(self, timer): + self._timers.add_timer(timer) + + # This function is called from a different thread than the event loop + # thread, so for this call to be thread safe, we must wake up the loop + # in case it's stuck at a select + self.wake_loop() + + def _cleanup(self): + global _dispatcher_map + + self._shutdown = True + if not self._thread: + return + + log.debug("Waiting for event loop thread to join...") + self._thread.join(timeout=1.0) + if self._thread.is_alive(): + log.warning( + "Event loop thread could not be joined, so shutdown may not be clean. " + "Please call Cluster.shutdown() to avoid this.") + + log.debug("Event loop thread was joined") + + # Ensure all connections are closed and in-flight requests cancelled + for conn in tuple(_dispatcher_map.values()): + if conn is not self._loop_dispatcher: + conn.close() + self._timers.service_timeouts() + # Once all the connections are closed, close the dispatcher + self._loop_dispatcher.close() + + log.debug("Dispatchers were closed") + + +_global_loop = None +atexit.register(partial(_cleanup, _global_loop)) + + +class AsyncoreConnection(Connection, asyncore.dispatcher): + """ + An implementation of :class:`.Connection` that uses the ``asyncore`` + module in the Python standard library for its event loop. + """ + + _writable = False + _readable = False + + @classmethod + def initialize_reactor(cls): + global _global_loop + if not _global_loop: + _global_loop = AsyncoreLoop() + else: + current_pid = os.getpid() + if _global_loop._pid != current_pid: + log.debug("Detected fork, clearing and reinitializing reactor state") + cls.handle_fork() + _global_loop = AsyncoreLoop() + + @classmethod + def handle_fork(cls): + global _dispatcher_map, _global_loop + _dispatcher_map = {} + if _global_loop: + _global_loop._cleanup() + _global_loop = None + + @classmethod + def create_timer(cls, timeout, callback): + timer = Timer(timeout, callback) + _global_loop.add_timer(timer) + return timer + + def __init__(self, *args, **kwargs): + Connection.__init__(self, *args, **kwargs) + + self.deque = deque() + self.deque_lock = Lock() + + self._connect_socket() + + # start the event loop if needed + _global_loop.maybe_start() + + init_handler = WaitableTimer( + timeout=0, + callback=partial(asyncore.dispatcher.__init__, + self, self._socket, _dispatcher_map) + ) + _global_loop.add_timer(init_handler) + init_handler.wait(kwargs["connect_timeout"]) + + self._writable = True + self._readable = True + + self._send_options_message() + + def close(self): + with self.lock: + if self.is_closed: + return + self.is_closed = True + + log.debug("Closing connection (%s) to %s", id(self), self.endpoint) + self._writable = False + self._readable = False + + # We don't have to wait for this to be closed, we can just schedule it + self.create_timer(0, partial(asyncore.dispatcher.close, self)) + + log.debug("Closed socket to %s", self.endpoint) + + if not self.is_defunct: + self.error_all_requests( + ConnectionShutdown("Connection to %s was closed" % self.endpoint)) + + #This happens when the connection is shutdown while waiting for the ReadyMessage + if not self.connected_event.is_set(): + self.last_error = ConnectionShutdown("Connection to %s was closed" % self.endpoint) + + # don't leave in-progress operations hanging + self.connected_event.set() + + def handle_error(self): + self.defunct(sys.exc_info()[1]) + + def handle_close(self): + log.debug("Connection %s closed by server", self) + self.close() + + def handle_write(self): + while True: + with self.deque_lock: + try: + next_msg = self.deque.popleft() + except IndexError: + self._writable = False + return + + try: + sent = self.send(next_msg) + self._readable = True + except socket.error as err: + if (err.args[0] in NONBLOCKING or + err.args[0] in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE)): + with self.deque_lock: + self.deque.appendleft(next_msg) + else: + self.defunct(err) + return + else: + if sent < len(next_msg): + with self.deque_lock: + self.deque.appendleft(next_msg[sent:]) + if sent == 0: + return + + def handle_read(self): + try: + while True: + buf = self.recv(self.in_buffer_size) + self._iobuf.write(buf) + if len(buf) < self.in_buffer_size: + break + except socket.error as err: + if isinstance(err, ssl.SSLError): + if err.args[0] in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE): + if not self._iobuf.tell(): + return + else: + self.defunct(err) + return + elif err.args[0] in NONBLOCKING: + if not self._iobuf.tell(): + return + else: + self.defunct(err) + return + + if self._iobuf.tell(): + self.process_io_buffer() + if not self._requests and not self.is_control_connection: + self._readable = False + + def push(self, data): + sabs = self.out_buffer_size + if len(data) > sabs: + chunks = [] + for i in range(0, len(data), sabs): + chunks.append(data[i:i + sabs]) + else: + chunks = [data] + + with self.deque_lock: + self.deque.extend(chunks) + self._writable = True + _global_loop.wake_loop() + + def writable(self): + return self._writable + + def readable(self): + return self._readable or ((self.is_control_connection or self._continuous_paging_sessions) and not (self.is_defunct or self.is_closed)) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/eventletreactor.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/eventletreactor.py new file mode 100644 index 0000000000000000000000000000000000000000..42874036d512db220c69776e83edd1c5f59a6036 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/eventletreactor.py @@ -0,0 +1,192 @@ +# Copyright 2014 Symantec Corporation +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Originally derived from MagnetoDB source: +# https://github.com/stackforge/magnetodb/blob/2015.1.0b1/magnetodb/common/cassandra/io/eventletreactor.py +import eventlet +from eventlet.green import socket +from eventlet.queue import Queue +from greenlet import GreenletExit +import logging +from threading import Event +import time + +from cassandra.connection import Connection, ConnectionShutdown, Timer, TimerManager +try: + from eventlet.green.OpenSSL import SSL + _PYOPENSSL = True +except ImportError as e: + _PYOPENSSL = False + no_pyopenssl_error = e + + +log = logging.getLogger(__name__) + + +def _check_pyopenssl(): + if not _PYOPENSSL: + raise ImportError( + "{}, pyOpenSSL must be installed to enable " + "SSL support with the Eventlet event loop".format(str(no_pyopenssl_error)) + ) + + +class EventletConnection(Connection): + """ + An implementation of :class:`.Connection` that utilizes ``eventlet``. + + This implementation assumes all eventlet monkey patching is active. It is not tested with partial patching. + """ + + _read_watcher = None + _write_watcher = None + + _socket_impl = eventlet.green.socket + _ssl_impl = eventlet.green.ssl + + _timers = None + _timeout_watcher = None + _new_timer = None + + @classmethod + def initialize_reactor(cls): + eventlet.monkey_patch() + if not cls._timers: + cls._timers = TimerManager() + cls._timeout_watcher = eventlet.spawn(cls.service_timeouts) + cls._new_timer = Event() + + @classmethod + def create_timer(cls, timeout, callback): + timer = Timer(timeout, callback) + cls._timers.add_timer(timer) + cls._new_timer.set() + return timer + + @classmethod + def service_timeouts(cls): + """ + cls._timeout_watcher runs in this loop forever. + It is usually waiting for the next timeout on the cls._new_timer Event. + When new timers are added, that event is set so that the watcher can + wake up and possibly set an earlier timeout. + """ + timer_manager = cls._timers + while True: + next_end = timer_manager.service_timeouts() + sleep_time = max(next_end - time.time(), 0) if next_end else 10000 + cls._new_timer.wait(sleep_time) + cls._new_timer.clear() + + def __init__(self, *args, **kwargs): + Connection.__init__(self, *args, **kwargs) + self.uses_legacy_ssl_options = self.ssl_options and not self.ssl_context + self._write_queue = Queue() + + self._connect_socket() + + self._read_watcher = eventlet.spawn(lambda: self.handle_read()) + self._write_watcher = eventlet.spawn(lambda: self.handle_write()) + self._send_options_message() + + def _wrap_socket_from_context(self): + _check_pyopenssl() + self._socket = SSL.Connection(self.ssl_context, self._socket) + self._socket.set_connect_state() + if self.ssl_options and 'server_hostname' in self.ssl_options: + # This is necessary for SNI + self._socket.set_tlsext_host_name(self.ssl_options['server_hostname'].encode('ascii')) + + def _initiate_connection(self, sockaddr): + if self.uses_legacy_ssl_options: + super(EventletConnection, self)._initiate_connection(sockaddr) + else: + self._socket.connect(sockaddr) + if self.ssl_context or self.ssl_options: + self._socket.do_handshake() + + def _match_hostname(self): + if self.uses_legacy_ssl_options: + super(EventletConnection, self)._match_hostname() + else: + cert_name = self._socket.get_peer_certificate().get_subject().commonName + if cert_name != self.endpoint.address: + raise Exception("Hostname verification failed! Certificate name '{}' " + "doesn't endpoint '{}'".format(cert_name, self.endpoint.address)) + + def close(self): + with self.lock: + if self.is_closed: + return + self.is_closed = True + + log.debug("Closing connection (%s) to %s" % (id(self), self.endpoint)) + + cur_gthread = eventlet.getcurrent() + + if self._read_watcher and self._read_watcher != cur_gthread: + self._read_watcher.kill() + if self._write_watcher and self._write_watcher != cur_gthread: + self._write_watcher.kill() + if self._socket: + self._socket.close() + log.debug("Closed socket to %s" % (self.endpoint,)) + + if not self.is_defunct: + self.error_all_requests( + ConnectionShutdown("Connection to %s was closed" % self.endpoint)) + # don't leave in-progress operations hanging + self.connected_event.set() + + def handle_close(self): + log.debug("connection closed by server") + self.close() + + def handle_write(self): + while True: + try: + next_msg = self._write_queue.get() + self._socket.sendall(next_msg) + except socket.error as err: + log.debug("Exception during socket send for %s: %s", self, err) + self.defunct(err) + return # Leave the write loop + except GreenletExit: # graceful greenthread exit + return + + def handle_read(self): + while True: + try: + buf = self._socket.recv(self.in_buffer_size) + self._iobuf.write(buf) + except socket.error as err: + log.debug("Exception during socket recv for %s: %s", + self, err) + self.defunct(err) + return # leave the read loop + except GreenletExit: # graceful greenthread exit + return + + if buf and self._iobuf.tell(): + self.process_io_buffer() + else: + log.debug("Connection %s closed by server", self) + self.close() + return + + def push(self, data): + chunk_size = self.out_buffer_size + for i in range(0, len(data), chunk_size): + self._write_queue.put(data[i:i + chunk_size]) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/geventreactor.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/geventreactor.py new file mode 100644 index 0000000000000000000000000000000000000000..4f1f158aa7f514f69f6276ddef39e03710595129 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/geventreactor.py @@ -0,0 +1,137 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import gevent +import gevent.event +from gevent.queue import Queue +from gevent import socket +import gevent.ssl + +import logging +import time + + +from cassandra.connection import Connection, ConnectionShutdown, Timer, TimerManager + + +log = logging.getLogger(__name__) + + +class GeventConnection(Connection): + """ + An implementation of :class:`.Connection` that utilizes ``gevent``. + + This implementation assumes all gevent monkey patching is active. It is not tested with partial patching. + """ + + _read_watcher = None + _write_watcher = None + + _socket_impl = gevent.socket + _ssl_impl = gevent.ssl + + _timers = None + _timeout_watcher = None + _new_timer = None + + @classmethod + def initialize_reactor(cls): + if not cls._timers: + cls._timers = TimerManager() + cls._timeout_watcher = gevent.spawn(cls.service_timeouts) + cls._new_timer = gevent.event.Event() + + @classmethod + def create_timer(cls, timeout, callback): + timer = Timer(timeout, callback) + cls._timers.add_timer(timer) + cls._new_timer.set() + return timer + + @classmethod + def service_timeouts(cls): + timer_manager = cls._timers + timer_event = cls._new_timer + while True: + next_end = timer_manager.service_timeouts() + sleep_time = max(next_end - time.time(), 0) if next_end else 10000 + timer_event.wait(sleep_time) + timer_event.clear() + + def __init__(self, *args, **kwargs): + Connection.__init__(self, *args, **kwargs) + + self._write_queue = Queue() + + self._connect_socket() + + self._read_watcher = gevent.spawn(self.handle_read) + self._write_watcher = gevent.spawn(self.handle_write) + self._send_options_message() + + def close(self): + with self.lock: + if self.is_closed: + return + self.is_closed = True + + log.debug("Closing connection (%s) to %s" % (id(self), self.endpoint)) + if self._read_watcher: + self._read_watcher.kill(block=False) + if self._write_watcher: + self._write_watcher.kill(block=False) + if self._socket: + self._socket.close() + log.debug("Closed socket to %s" % (self.endpoint,)) + + if not self.is_defunct: + self.error_all_requests( + ConnectionShutdown("Connection to %s was closed" % self.endpoint)) + # don't leave in-progress operations hanging + self.connected_event.set() + + def handle_close(self): + log.debug("connection closed by server") + self.close() + + def handle_write(self): + while True: + try: + next_msg = self._write_queue.get() + self._socket.sendall(next_msg) + except socket.error as err: + log.debug("Exception in send for %s: %s", self, err) + self.defunct(err) + return + + def handle_read(self): + while True: + try: + buf = self._socket.recv(self.in_buffer_size) + self._iobuf.write(buf) + except socket.error as err: + log.debug("Exception in read for %s: %s", self, err) + self.defunct(err) + return # leave the read loop + + if buf and self._iobuf.tell(): + self.process_io_buffer() + else: + log.debug("Connection %s closed by server", self) + self.close() + return + + def push(self, data): + chunk_size = self.out_buffer_size + for i in range(0, len(data), chunk_size): + self._write_queue.put(data[i:i + chunk_size]) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/libevreactor.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/libevreactor.py new file mode 100644 index 0000000000000000000000000000000000000000..58c876fdcc94e96d51e50ae8814f8a29987441be --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/libevreactor.py @@ -0,0 +1,392 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import atexit +from collections import deque +from functools import partial +import logging +import os +import socket +import ssl +from threading import Lock, Thread +import time + +from cassandra import DependencyException +try: + import cassandra.io.libevwrapper as libev +except ImportError: + raise DependencyException( + "The C extension needed to use libev was not found. This " + "probably means that you didn't have the required build dependencies " + "when installing the driver. See " + "http://datastax.github.io/python-driver/installation.html#c-extensions " + "for instructions on installing build dependencies and building " + "the C extension.") + +from cassandra.connection import (Connection, ConnectionShutdown, + NONBLOCKING, Timer, TimerManager) + + +log = logging.getLogger(__name__) + + +def _cleanup(loop): + if loop: + loop._cleanup() + + +class LibevLoop(object): + + def __init__(self): + self._pid = os.getpid() + self._loop = libev.Loop() + self._notifier = libev.Async(self._loop) + self._notifier.start() + + # prevent _notifier from keeping the loop from returning + self._loop.unref() + + self._started = False + self._shutdown = False + self._lock = Lock() + self._lock_thread = Lock() + + self._thread = None + + # set of all connections; only replaced with a new copy + # while holding _conn_set_lock, never modified in place + self._live_conns = set() + # newly created connections that need their write/read watcher started + self._new_conns = set() + # recently closed connections that need their write/read watcher stopped + self._closed_conns = set() + self._conn_set_lock = Lock() + + self._preparer = libev.Prepare(self._loop, self._loop_will_run) + # prevent _preparer from keeping the loop from returning + self._loop.unref() + self._preparer.start() + + self._timers = TimerManager() + self._loop_timer = libev.Timer(self._loop, self._on_loop_timer) + + def maybe_start(self): + should_start = False + with self._lock: + if not self._started: + log.debug("Starting libev event loop") + self._started = True + should_start = True + + if should_start: + with self._lock_thread: + if not self._shutdown: + self._thread = Thread(target=self._run_loop, name="event_loop") + self._thread.daemon = True + self._thread.start() + + self._notifier.send() + + def _run_loop(self): + while True: + self._loop.start() + # there are still active watchers, no deadlock + with self._lock: + if not self._shutdown and self._live_conns: + log.debug("Restarting event loop") + continue + else: + # all Connections have been closed, no active watchers + log.debug("All Connections currently closed, event loop ended") + self._started = False + break + + def _cleanup(self): + self._shutdown = True + if not self._thread: + return + + for conn in self._live_conns | self._new_conns | self._closed_conns: + conn.close() + for watcher in (conn._write_watcher, conn._read_watcher): + if watcher: + watcher.stop() + + self.notify() # wake the timer watcher + + # PYTHON-752 Thread might have just been created and not started + with self._lock_thread: + self._thread.join(timeout=1.0) + + if self._thread.is_alive(): + log.warning( + "Event loop thread could not be joined, so shutdown may not be clean. " + "Please call Cluster.shutdown() to avoid this.") + + log.debug("Event loop thread was joined") + + def add_timer(self, timer): + self._timers.add_timer(timer) + self._notifier.send() # wake up in case this timer is earlier + + def _update_timer(self): + if not self._shutdown: + next_end = self._timers.service_timeouts() + if next_end: + self._loop_timer.start(next_end - time.time()) # timer handles negative values + else: + self._loop_timer.stop() + + def _on_loop_timer(self): + self._timers.service_timeouts() + + def notify(self): + self._notifier.send() + + def connection_created(self, conn): + with self._conn_set_lock: + new_live_conns = self._live_conns.copy() + new_live_conns.add(conn) + self._live_conns = new_live_conns + + new_new_conns = self._new_conns.copy() + new_new_conns.add(conn) + self._new_conns = new_new_conns + + def connection_destroyed(self, conn): + with self._conn_set_lock: + new_conns = self._new_conns.copy() + new_conns.discard(conn) + self._new_conns = new_conns + + new_live_conns = self._live_conns.copy() + new_live_conns.discard(conn) + self._live_conns = new_live_conns + + new_closed_conns = self._closed_conns.copy() + new_closed_conns.add(conn) + self._closed_conns = new_closed_conns + + self._notifier.send() + + def _loop_will_run(self, prepare): + changed = False + for conn in self._live_conns: + if not conn.deque and conn._write_watcher_is_active: + if conn._write_watcher: + conn._write_watcher.stop() + conn._write_watcher_is_active = False + changed = True + elif conn.deque and not conn._write_watcher_is_active: + conn._write_watcher.start() + conn._write_watcher_is_active = True + changed = True + + if self._new_conns: + with self._conn_set_lock: + to_start = self._new_conns + self._new_conns = set() + + for conn in to_start: + if conn._read_watcher: + conn._read_watcher.start() + + changed = True + + if self._closed_conns: + with self._conn_set_lock: + to_stop = self._closed_conns + self._closed_conns = set() + + for conn in to_stop: + if conn._write_watcher: + conn._write_watcher.stop() + # clear reference cycles from IO callback + del conn._write_watcher + if conn._read_watcher: + conn._read_watcher.stop() + # clear reference cycles from IO callback + del conn._read_watcher + + changed = True + + # TODO: update to do connection management, timer updates through dedicated async 'notifier' callbacks + self._update_timer() + + if changed: + self._notifier.send() + + +_global_loop = None +atexit.register(partial(_cleanup, _global_loop)) + + +class LibevConnection(Connection): + """ + An implementation of :class:`.Connection` that uses libev for its event loop. + """ + _write_watcher_is_active = False + _read_watcher = None + _write_watcher = None + _socket = None + + @classmethod + def initialize_reactor(cls): + global _global_loop + if not _global_loop: + _global_loop = LibevLoop() + else: + if _global_loop._pid != os.getpid(): + log.debug("Detected fork, clearing and reinitializing reactor state") + cls.handle_fork() + _global_loop = LibevLoop() + + @classmethod + def handle_fork(cls): + global _global_loop + if _global_loop: + _global_loop._cleanup() + _global_loop = None + + @classmethod + def create_timer(cls, timeout, callback): + timer = Timer(timeout, callback) + _global_loop.add_timer(timer) + return timer + + def __init__(self, *args, **kwargs): + Connection.__init__(self, *args, **kwargs) + + self.deque = deque() + self._deque_lock = Lock() + self._connect_socket() + self._socket.setblocking(0) + + with _global_loop._lock: + self._read_watcher = libev.IO(self._socket.fileno(), libev.EV_READ, _global_loop._loop, self.handle_read) + self._write_watcher = libev.IO(self._socket.fileno(), libev.EV_WRITE, _global_loop._loop, self.handle_write) + + self._send_options_message() + + _global_loop.connection_created(self) + + # start the global event loop if needed + _global_loop.maybe_start() + + def close(self): + with self.lock: + if self.is_closed: + return + self.is_closed = True + + log.debug("Closing connection (%s) to %s", id(self), self.endpoint) + + _global_loop.connection_destroyed(self) + self._socket.close() + log.debug("Closed socket to %s", self.endpoint) + + # don't leave in-progress operations hanging + if not self.is_defunct: + self.error_all_requests( + ConnectionShutdown("Connection to %s was closed" % self.endpoint)) + self.connected_event.set() + + def handle_write(self, watcher, revents, errno=None): + if revents & libev.EV_ERROR: + if errno: + exc = IOError(errno, os.strerror(errno)) + else: + exc = Exception("libev reported an error") + + self.defunct(exc) + return + + while True: + try: + with self._deque_lock: + next_msg = self.deque.popleft() + except IndexError: + if not self._socket_writable: + self._socket_writable = True + return + + try: + sent = self._socket.send(next_msg) + except socket.error as err: + if (err.args[0] in NONBLOCKING or + err.args[0] in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE)): + if err.args[0] in NONBLOCKING: + self._socket_writable = False + with self._deque_lock: + self.deque.appendleft(next_msg) + else: + self.defunct(err) + return + else: + if sent < len(next_msg): + with self._deque_lock: + self.deque.appendleft(next_msg[sent:]) + # we've seen some cases that 0 is returned instead of NONBLOCKING. But usually, + # we don't expect this to happen. https://bugs.python.org/issue20951 + if sent == 0: + self._socket_writable = False + return + + def handle_read(self, watcher, revents, errno=None): + if revents & libev.EV_ERROR: + if errno: + exc = IOError(errno, os.strerror(errno)) + else: + exc = Exception("libev reported an error") + + self.defunct(exc) + return + try: + while True: + buf = self._socket.recv(self.in_buffer_size) + self._iobuf.write(buf) + if len(buf) < self.in_buffer_size: + break + except socket.error as err: + if isinstance(err, ssl.SSLError): + if err.args[0] in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE): + if not self._iobuf.tell(): + return + else: + self.defunct(err) + return + elif err.args[0] in NONBLOCKING: + if not self._iobuf.tell(): + return + else: + self.defunct(err) + return + + if self._iobuf.tell(): + self.process_io_buffer() + else: + log.debug("Connection %s closed by server", self) + self.close() + + def push(self, data): + sabs = self.out_buffer_size + if len(data) > sabs: + chunks = [] + for i in range(0, len(data), sabs): + chunks.append(data[i:i + sabs]) + else: + chunks = [data] + + with self._deque_lock: + self.deque.extend(chunks) + _global_loop.notify() diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/libevwrapper.c b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/libevwrapper.c new file mode 100644 index 0000000000000000000000000000000000000000..f32504fa342ca87a8a4f2f60ae3989046655da7c --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/libevwrapper.c @@ -0,0 +1,674 @@ +#pragma comment(lib, "Ws2_32.Lib") + +#include +#include + +typedef struct libevwrapper_Loop { + PyObject_HEAD + struct ev_loop *loop; +} libevwrapper_Loop; + +static void +Loop_dealloc(libevwrapper_Loop *self) { + ev_loop_destroy(self->loop); + Py_TYPE(self)->tp_free((PyObject *)self); +}; + +static PyObject* +Loop_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { + libevwrapper_Loop *self; + + self = (libevwrapper_Loop *)type->tp_alloc(type, 0); + if (self != NULL) { + self->loop = ev_loop_new(EVBACKEND_SELECT); + if (!self->loop) { + PyErr_SetString(PyExc_Exception, "Error getting new ev loop"); + Py_DECREF(self); + return NULL; + } + } + return (PyObject *)self; +}; + +static int +Loop_init(libevwrapper_Loop *self, PyObject *args, PyObject *kwds) { + if (!PyArg_ParseTuple(args, "")) { + PyErr_SetString(PyExc_TypeError, "Loop.__init__() takes no arguments"); + return -1; + } + return 0; +}; + +static PyObject * +Loop_start(libevwrapper_Loop *self, PyObject *args) { + Py_BEGIN_ALLOW_THREADS + ev_run(self->loop, 0); + Py_END_ALLOW_THREADS + Py_RETURN_NONE; +}; + +static PyObject * +Loop_unref(libevwrapper_Loop *self, PyObject *args) { + ev_unref(self->loop); + Py_RETURN_NONE; +} + +static PyMethodDef Loop_methods[] = { + {"start", (PyCFunction)Loop_start, METH_NOARGS, "Start the event loop"}, + {"unref", (PyCFunction)Loop_unref, METH_NOARGS, "Unrefrence the event loop"}, + {NULL} /* Sentinel */ +}; + +static +PyTypeObject libevwrapper_LoopType = { + PyVarObject_HEAD_INIT(NULL, 0) + "cassandra.io.libevwrapper.Loop",/*tp_name*/ + sizeof(libevwrapper_Loop), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + (destructor)Loop_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash */ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "Loop objects", /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + Loop_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)Loop_init, /* tp_init */ + 0, /* tp_alloc */ + Loop_new, /* tp_new */ +}; + +typedef struct libevwrapper_IO { + PyObject_HEAD + struct ev_io io; + struct libevwrapper_Loop *loop; + PyObject *callback; +} libevwrapper_IO; + +static void +IO_dealloc(libevwrapper_IO *self) { + Py_XDECREF(self->loop); + Py_XDECREF(self->callback); + Py_TYPE(self)->tp_free((PyObject *)self); +}; + +static void io_callback(struct ev_loop *loop, ev_io *watcher, int revents) { + libevwrapper_IO *self = watcher->data; + PyObject *result; + PyGILState_STATE gstate = PyGILState_Ensure(); + if (revents & EV_ERROR && errno) { + result = PyObject_CallFunction(self->callback, "Obi", self, revents, errno); + } else { + result = PyObject_CallFunction(self->callback, "Ob", self, revents); + } + if (!result) { + PyErr_WriteUnraisable(self->callback); + } + Py_XDECREF(result); + PyGILState_Release(gstate); +}; + +static int +IO_init(libevwrapper_IO *self, PyObject *args, PyObject *kwds) { + PyObject *socket; + PyObject *callback; + PyObject *loop; + int io_flags = 0, fd = -1; + struct ev_io *io = NULL; + + if (!PyArg_ParseTuple(args, "OiOO", &socket, &io_flags, &loop, &callback)) { + return -1; + } + + if (loop) { + Py_INCREF(loop); + self->loop = (libevwrapper_Loop *)loop; + } + + if (callback) { + if (!PyCallable_Check(callback)) { + PyErr_SetString(PyExc_TypeError, "callback parameter must be callable"); + Py_XDECREF(loop); + return -1; + } + Py_INCREF(callback); + self->callback = callback; + } + + fd = PyObject_AsFileDescriptor(socket); + if (fd == -1) { + PyErr_SetString(PyExc_TypeError, "unable to get file descriptor from socket"); + Py_XDECREF(callback); + Py_XDECREF(loop); + return -1; + } + io = &(self->io); + ev_io_init(io, io_callback, fd, io_flags); + self->io.data = self; + return 0; +} + +static PyObject* +IO_start(libevwrapper_IO *self, PyObject *args) { + ev_io_start(self->loop->loop, &self->io); + Py_RETURN_NONE; +} + +static PyObject* +IO_stop(libevwrapper_IO *self, PyObject *args) { + ev_io_stop(self->loop->loop, &self->io); + Py_RETURN_NONE; +} + +static PyObject* +IO_is_active(libevwrapper_IO *self, PyObject *args) { + struct ev_io *io = &(self->io); + return PyBool_FromLong(ev_is_active(io)); +} + +static PyObject* +IO_is_pending(libevwrapper_IO *self, PyObject *args) { + struct ev_io *io = &(self->io); + return PyBool_FromLong(ev_is_pending(io)); +} + +static PyMethodDef IO_methods[] = { + {"start", (PyCFunction)IO_start, METH_NOARGS, "Start the watcher"}, + {"stop", (PyCFunction)IO_stop, METH_NOARGS, "Stop the watcher"}, + {"is_active", (PyCFunction)IO_is_active, METH_NOARGS, "Is the watcher active?"}, + {"is_pending", (PyCFunction)IO_is_pending, METH_NOARGS, "Is the watcher pending?"}, + {NULL} /* Sentinal */ +}; + +static PyTypeObject libevwrapper_IOType = { + PyVarObject_HEAD_INIT(NULL, 0) + "cassandra.io.libevwrapper.IO", /*tp_name*/ + sizeof(libevwrapper_IO), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + (destructor)IO_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash */ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "IO objects", /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + IO_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)IO_init, /* tp_init */ +}; + +typedef struct libevwrapper_Async { + PyObject_HEAD + struct ev_async async; + struct libevwrapper_Loop *loop; +} libevwrapper_Async; + +static void +Async_dealloc(libevwrapper_Async *self) { + Py_XDECREF(self->loop); + Py_TYPE(self)->tp_free((PyObject *)self); +}; + +static void async_callback(EV_P_ ev_async *watcher, int revents) {}; + +static int +Async_init(libevwrapper_Async *self, PyObject *args, PyObject *kwds) { + PyObject *loop; + static char *kwlist[] = {"loop", NULL}; + struct ev_async *async = NULL; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O", kwlist, &loop)) { + PyErr_SetString(PyExc_TypeError, "unable to get file descriptor from socket"); + return -1; + } + + if (loop) { + Py_INCREF(loop); + self->loop = (libevwrapper_Loop *)loop; + } else { + return -1; + } + async = &(self->async); + ev_async_init(async, async_callback); + return 0; +}; + +static PyObject * +Async_start(libevwrapper_Async *self, PyObject *args) { + ev_async_start(self->loop->loop, &self->async); + Py_RETURN_NONE; +} + +static PyObject * +Async_send(libevwrapper_Async *self, PyObject *args) { + ev_async_send(self->loop->loop, &self->async); + Py_RETURN_NONE; +}; + +static PyMethodDef Async_methods[] = { + {"start", (PyCFunction)Async_start, METH_NOARGS, "Start the watcher"}, + {"send", (PyCFunction)Async_send, METH_NOARGS, "Notify the event loop"}, + {NULL} /* Sentinel */ +}; + +static PyTypeObject libevwrapper_AsyncType = { + PyVarObject_HEAD_INIT(NULL, 0) + "cassandra.io.libevwrapper.Async", /*tp_name*/ + sizeof(libevwrapper_Async), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + (destructor)Async_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash */ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "Async objects", /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + Async_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)Async_init, /* tp_init */ +}; + +typedef struct libevwrapper_Prepare { + PyObject_HEAD + struct ev_prepare prepare; + struct libevwrapper_Loop *loop; + PyObject *callback; +} libevwrapper_Prepare; + +static void +Prepare_dealloc(libevwrapper_Prepare *self) { + Py_XDECREF(self->loop); + Py_XDECREF(self->callback); + Py_TYPE(self)->tp_free((PyObject *)self); +} + +static void prepare_callback(struct ev_loop *loop, ev_prepare *watcher, int revents) { + libevwrapper_Prepare *self = watcher->data; + PyObject *result = NULL; + PyGILState_STATE gstate; + + gstate = PyGILState_Ensure(); + result = PyObject_CallFunction(self->callback, "O", self); + if (!result) { + PyErr_WriteUnraisable(self->callback); + } + Py_XDECREF(result); + + PyGILState_Release(gstate); +} + +static int +Prepare_init(libevwrapper_Prepare *self, PyObject *args, PyObject *kwds) { + PyObject *callback; + PyObject *loop; + struct ev_prepare *prepare = NULL; + + if (!PyArg_ParseTuple(args, "OO", &loop, &callback)) { + return -1; + } + + if (loop) { + Py_INCREF(loop); + self->loop = (libevwrapper_Loop *)loop; + } else { + return -1; + } + + if (callback) { + if (!PyCallable_Check(callback)) { + PyErr_SetString(PyExc_TypeError, "callback parameter must be callable"); + Py_XDECREF(loop); + return -1; + } + Py_INCREF(callback); + self->callback = callback; + } + prepare = &(self->prepare); + ev_prepare_init(prepare, prepare_callback); + self->prepare.data = self; + return 0; +} + +static PyObject * +Prepare_start(libevwrapper_Prepare *self, PyObject *args) { + ev_prepare_start(self->loop->loop, &self->prepare); + Py_RETURN_NONE; +} + +static PyObject * +Prepare_stop(libevwrapper_Prepare *self, PyObject *args) { + ev_prepare_stop(self->loop->loop, &self->prepare); + Py_RETURN_NONE; +} + +static PyMethodDef Prepare_methods[] = { + {"start", (PyCFunction)Prepare_start, METH_NOARGS, "Start the Prepare watcher"}, + {"stop", (PyCFunction)Prepare_stop, METH_NOARGS, "Stop the Prepare watcher"}, + {NULL} /* Sentinal */ +}; + +static PyTypeObject libevwrapper_PrepareType = { + PyVarObject_HEAD_INIT(NULL, 0) + "cassandra.io.libevwrapper.Prepare", /*tp_name*/ + sizeof(libevwrapper_Prepare), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + (destructor)Prepare_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash */ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "Prepare objects", /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + Prepare_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)Prepare_init, /* tp_init */ +}; + +typedef struct libevwrapper_Timer { + PyObject_HEAD + struct ev_timer timer; + struct libevwrapper_Loop *loop; + PyObject *callback; +} libevwrapper_Timer; + +static void +Timer_dealloc(libevwrapper_Timer *self) { + Py_XDECREF(self->loop); + Py_XDECREF(self->callback); + Py_TYPE(self)->tp_free((PyObject *)self); +} + +static void timer_callback(struct ev_loop *loop, ev_timer *watcher, int revents) { + libevwrapper_Timer *self = watcher->data; + + PyObject *result = NULL; + PyGILState_STATE gstate; + + gstate = PyGILState_Ensure(); + result = PyObject_CallFunction(self->callback, NULL); + if (!result) { + PyErr_WriteUnraisable(self->callback); + } + Py_XDECREF(result); + + PyGILState_Release(gstate); +} + +static int +Timer_init(libevwrapper_Timer *self, PyObject *args, PyObject *kwds) { + PyObject *callback; + PyObject *loop; + + if (!PyArg_ParseTuple(args, "OO", &loop, &callback)) { + return -1; + } + + if (loop) { + Py_INCREF(loop); + self->loop = (libevwrapper_Loop *)loop; + } else { + return -1; + } + + if (callback) { + if (!PyCallable_Check(callback)) { + PyErr_SetString(PyExc_TypeError, "callback parameter must be callable"); + Py_XDECREF(loop); + return -1; + } + Py_INCREF(callback); + self->callback = callback; + } + ev_init(&self->timer, timer_callback); + self->timer.data = self; + return 0; +} + +static PyObject * +Timer_start(libevwrapper_Timer *self, PyObject *args) { + double timeout; + if (!PyArg_ParseTuple(args, "d", &timeout)) { + return NULL; + } + /* some tiny non-zero number to avoid zero, and + make it run immediately for negative timeouts */ + self->timer.repeat = fmax(timeout, 0.000000001); + ev_timer_again(self->loop->loop, &self->timer); + Py_RETURN_NONE; +} + +static PyObject * +Timer_stop(libevwrapper_Timer *self, PyObject *args) { + ev_timer_stop(self->loop->loop, &self->timer); + Py_RETURN_NONE; +} + +static PyMethodDef Timer_methods[] = { + {"start", (PyCFunction)Timer_start, METH_VARARGS, "Start the Timer watcher"}, + {"stop", (PyCFunction)Timer_stop, METH_NOARGS, "Stop the Timer watcher"}, + {NULL} /* Sentinal */ +}; + +static PyTypeObject libevwrapper_TimerType = { + PyVarObject_HEAD_INIT(NULL, 0) + "cassandra.io.libevwrapper.Timer", /*tp_name*/ + sizeof(libevwrapper_Timer), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + (destructor)Timer_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash */ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "Timer objects", /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + Timer_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)Timer_init, /* tp_init */ +}; + + +static PyMethodDef module_methods[] = { + {NULL} /* Sentinal */ +}; + +PyDoc_STRVAR(module_doc, +"libev wrapper methods"); + +#if PY_MAJOR_VERSION >= 3 +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + "libevwrapper", + module_doc, + -1, + module_methods, + NULL, + NULL, + NULL, + NULL +}; + +#define INITERROR return NULL + +PyObject * +PyInit_libevwrapper(void) + +# else +# define INITERROR return + +void +initlibevwrapper(void) +#endif +{ + PyObject *module = NULL; + + if (PyType_Ready(&libevwrapper_LoopType) < 0) + INITERROR; + + libevwrapper_IOType.tp_new = PyType_GenericNew; + if (PyType_Ready(&libevwrapper_IOType) < 0) + INITERROR; + + libevwrapper_PrepareType.tp_new = PyType_GenericNew; + if (PyType_Ready(&libevwrapper_PrepareType) < 0) + INITERROR; + + libevwrapper_AsyncType.tp_new = PyType_GenericNew; + if (PyType_Ready(&libevwrapper_AsyncType) < 0) + INITERROR; + + libevwrapper_TimerType.tp_new = PyType_GenericNew; + if (PyType_Ready(&libevwrapper_TimerType) < 0) + INITERROR; + +# if PY_MAJOR_VERSION >= 3 + module = PyModule_Create(&moduledef); +# else + module = Py_InitModule3("libevwrapper", module_methods, module_doc); +# endif + + if (module == NULL) + INITERROR; + + if (PyModule_AddIntConstant(module, "EV_READ", EV_READ) == -1) + INITERROR; + if (PyModule_AddIntConstant(module, "EV_WRITE", EV_WRITE) == -1) + INITERROR; + if (PyModule_AddIntConstant(module, "EV_ERROR", EV_ERROR) == -1) + INITERROR; + + Py_INCREF(&libevwrapper_LoopType); + if (PyModule_AddObject(module, "Loop", (PyObject *)&libevwrapper_LoopType) == -1) + INITERROR; + + Py_INCREF(&libevwrapper_IOType); + if (PyModule_AddObject(module, "IO", (PyObject *)&libevwrapper_IOType) == -1) + INITERROR; + + Py_INCREF(&libevwrapper_PrepareType); + if (PyModule_AddObject(module, "Prepare", (PyObject *)&libevwrapper_PrepareType) == -1) + INITERROR; + + Py_INCREF(&libevwrapper_AsyncType); + if (PyModule_AddObject(module, "Async", (PyObject *)&libevwrapper_AsyncType) == -1) + INITERROR; + + Py_INCREF(&libevwrapper_TimerType); + if (PyModule_AddObject(module, "Timer", (PyObject *)&libevwrapper_TimerType) == -1) + INITERROR; + + +#if PY_MAJOR_VERSION >= 3 + return module; +#endif +} diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/libevwrapper.cpython-312-x86_64-linux-gnu.so b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/libevwrapper.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..664d2a808607a41967bd699619cc7a2c42f9f990 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/libevwrapper.cpython-312-x86_64-linux-gnu.so differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/twistedreactor.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/twistedreactor.py new file mode 100644 index 0000000000000000000000000000000000000000..e4605a7446dff2fea81a1db5b53db3161a48c1b2 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/io/twistedreactor.py @@ -0,0 +1,306 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Module that implements an event loop based on twisted +( https://twistedmatrix.com ). +""" +import atexit +import logging +import time +from functools import partial +from threading import Thread, Lock +import weakref + +from twisted.internet import reactor, protocol +from twisted.internet.endpoints import connectProtocol, TCP4ClientEndpoint, SSL4ClientEndpoint +from twisted.internet.interfaces import IOpenSSLClientConnectionCreator +from twisted.python.failure import Failure +from zope.interface import implementer + +from cassandra.connection import Connection, ConnectionShutdown, Timer, TimerManager, ConnectionException + +try: + from OpenSSL import SSL + _HAS_SSL = True +except ImportError as e: + _HAS_SSL = False + import_exception = e +log = logging.getLogger(__name__) + + +def _cleanup(cleanup_weakref): + try: + cleanup_weakref()._cleanup() + except ReferenceError: + return + + +class TwistedConnectionProtocol(protocol.Protocol): + """ + Twisted Protocol class for handling data received and connection + made events. + """ + + def __init__(self, connection): + self.connection = connection + + def dataReceived(self, data): + """ + Callback function that is called when data has been received + on the connection. + + Reaches back to the Connection object and queues the data for + processing. + """ + self.connection._iobuf.write(data) + self.connection.handle_read() + + def connectionMade(self): + """ + Callback function that is called when a connection has succeeded. + + Reaches back to the Connection object and confirms that the connection + is ready. + """ + self.connection.client_connection_made(self.transport) + + def connectionLost(self, reason): + # reason is a Failure instance + log.debug("Connect lost: %s", reason) + self.connection.defunct(reason.value) + + +class TwistedLoop(object): + + _lock = None + _thread = None + _timeout_task = None + _timeout = None + + def __init__(self): + self._lock = Lock() + self._timers = TimerManager() + + def maybe_start(self): + with self._lock: + if not reactor.running: + self._thread = Thread(target=reactor.run, + name="cassandra_driver_twisted_event_loop", + kwargs={'installSignalHandlers': False}) + self._thread.daemon = True + self._thread.start() + atexit.register(partial(_cleanup, weakref.ref(self))) + + def _reactor_stopped(self): + return reactor._stopped + + def _cleanup(self): + if self._thread: + reactor.callFromThread(reactor.stop) + self._thread.join(timeout=1.0) + if self._thread.is_alive(): + log.warning("Event loop thread could not be joined, so " + "shutdown may not be clean. Please call " + "Cluster.shutdown() to avoid this.") + log.debug("Event loop thread was joined") + + def add_timer(self, timer): + self._timers.add_timer(timer) + # callFromThread to schedule from the loop thread, where + # the timeout task can safely be modified + reactor.callFromThread(self._schedule_timeout, timer.end) + + def _schedule_timeout(self, next_timeout): + if next_timeout: + delay = max(next_timeout - time.time(), 0) + if self._timeout_task and self._timeout_task.active(): + if next_timeout < self._timeout: + self._timeout_task.reset(delay) + self._timeout = next_timeout + else: + self._timeout_task = reactor.callLater(delay, self._on_loop_timer) + self._timeout = next_timeout + + def _on_loop_timer(self): + self._timers.service_timeouts() + self._schedule_timeout(self._timers.next_timeout) + + +@implementer(IOpenSSLClientConnectionCreator) +class _SSLCreator(object): + def __init__(self, endpoint, ssl_context, ssl_options, check_hostname, timeout): + self.endpoint = endpoint + self.ssl_options = ssl_options + self.check_hostname = check_hostname + self.timeout = timeout + + if ssl_context: + self.context = ssl_context + else: + self.context = SSL.Context(SSL.TLSv1_METHOD) + if "certfile" in self.ssl_options: + self.context.use_certificate_file(self.ssl_options["certfile"]) + if "keyfile" in self.ssl_options: + self.context.use_privatekey_file(self.ssl_options["keyfile"]) + if "ca_certs" in self.ssl_options: + self.context.load_verify_locations(self.ssl_options["ca_certs"]) + if "cert_reqs" in self.ssl_options: + self.context.set_verify( + self.ssl_options["cert_reqs"], + callback=self.verify_callback + ) + self.context.set_info_callback(self.info_callback) + + def verify_callback(self, connection, x509, errnum, errdepth, ok): + return ok + + def info_callback(self, connection, where, ret): + if where & SSL.SSL_CB_HANDSHAKE_DONE: + if self.check_hostname and self.endpoint.address != connection.get_peer_certificate().get_subject().commonName: + transport = connection.get_app_data() + transport.failVerification(Failure(ConnectionException("Hostname verification failed", self.endpoint))) + + def clientConnectionForTLS(self, tlsProtocol): + connection = SSL.Connection(self.context, None) + connection.set_app_data(tlsProtocol) + if self.ssl_options and "server_hostname" in self.ssl_options: + connection.set_tlsext_host_name(self.ssl_options['server_hostname'].encode('ascii')) + return connection + + +class TwistedConnection(Connection): + """ + An implementation of :class:`.Connection` that utilizes the + Twisted event loop. + """ + + _loop = None + + @classmethod + def initialize_reactor(cls): + if not cls._loop: + cls._loop = TwistedLoop() + + @classmethod + def create_timer(cls, timeout, callback): + timer = Timer(timeout, callback) + cls._loop.add_timer(timer) + return timer + + def __init__(self, *args, **kwargs): + """ + Initialization method. + + Note that we can't call reactor methods directly here because + it's not thread-safe, so we schedule the reactor/connection + stuff to be run from the event loop thread when it gets the + chance. + """ + Connection.__init__(self, *args, **kwargs) + + self.is_closed = True + self.connector = None + self.transport = None + + reactor.callFromThread(self.add_connection) + self._loop.maybe_start() + + def _check_pyopenssl(self): + if self.ssl_context or self.ssl_options: + if not _HAS_SSL: + raise ImportError( + str(import_exception) + + ', pyOpenSSL must be installed to enable SSL support with the Twisted event loop' + ) + + def add_connection(self): + """ + Convenience function to connect and store the resulting + connector. + """ + host, port = self.endpoint.resolve() + if self.ssl_context or self.ssl_options: + # Can't use optionsForClientTLS here because it *forces* hostname verification. + # Cool they enforce strong security, but we have to be able to turn it off + self._check_pyopenssl() + + ssl_connection_creator = _SSLCreator( + self.endpoint, + self.ssl_context if self.ssl_context else None, + self.ssl_options, + self._check_hostname, + self.connect_timeout, + ) + + endpoint = SSL4ClientEndpoint( + reactor, + host, + port, + sslContextFactory=ssl_connection_creator, + timeout=self.connect_timeout, + ) + else: + endpoint = TCP4ClientEndpoint( + reactor, + host, + port, + timeout=self.connect_timeout + ) + connectProtocol(endpoint, TwistedConnectionProtocol(self)) + + def client_connection_made(self, transport): + """ + Called by twisted protocol when a connection attempt has + succeeded. + """ + with self.lock: + self.is_closed = False + self.transport = transport + self._send_options_message() + + def close(self): + """ + Disconnect and error-out all requests. + """ + with self.lock: + if self.is_closed: + return + self.is_closed = True + + log.debug("Closing connection (%s) to %s", id(self), self.endpoint) + reactor.callFromThread(self.transport.connector.disconnect) + log.debug("Closed socket to %s", self.endpoint) + + if not self.is_defunct: + self.error_all_requests( + ConnectionShutdown("Connection to %s was closed" % self.endpoint)) + # don't leave in-progress operations hanging + self.connected_event.set() + + def handle_read(self): + """ + Process the incoming data buffer. + """ + self.process_io_buffer() + + def push(self, data): + """ + This function is called when outgoing data should be queued + for sending. + + Note that we can't call transport.write() directly because + it is not thread-safe, so we schedule it to run from within + the event loop when it gets the chance. + """ + reactor.callFromThread(self.transport.write, data) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/scylla/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/scylla/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/scylla/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/scylla/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9f3bac31eb9acc1abc1a4a39677afae409fa6d7 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/scylla/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/scylla/__pycache__/cloud.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/scylla/__pycache__/cloud.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89ed501c35b7d68f37751f30e424ef8b5895cf59 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/scylla/__pycache__/cloud.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/scylla/cloud.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/scylla/cloud.py new file mode 100644 index 0000000000000000000000000000000000000000..c3298b199a2edcbfd71914206925c4aa93c6c21b --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/scylla/cloud.py @@ -0,0 +1,139 @@ +# Copyright ScyllaDB, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import sys +import ssl +import tempfile +import base64 +from ssl import SSLContext +from contextlib import contextmanager +from itertools import islice + +import yaml + +from cassandra.connection import SniEndPointFactory +from cassandra.auth import AuthProvider, PlainTextAuthProvider + + +@contextmanager +def file_or_memory(path=None, data=None): + # since we can't read keys/cert from memory yet + # see https://github.com/python/cpython/pull/2449 which isn't accepted and PEP-543 that was withdrawn + # so we use temporary file to load the key + if data: + with tempfile.NamedTemporaryFile(mode="wb") as f: + d = base64.b64decode(data) + f.write(d) + if not d.endswith(b"\n"): + f.write(b"\n") + + f.flush() + yield f.name + + if path: + yield path + + +def nth(iterable, n, default=None): + "Returns the nth item or a default value" + return next(islice(iterable, n, None), default) + + +class CloudConfiguration: + endpoint_factory: SniEndPointFactory + contact_points: list + auth_provider: AuthProvider = None + ssl_options: dict + ssl_context: SSLContext + skip_tls_verify: bool + + def __init__(self, configuration_file, pyopenssl=False, endpoint_factory=None): + cloud_config = yaml.safe_load(open(configuration_file)) + + self.current_context = cloud_config['contexts'][cloud_config['currentContext']] + self.data_centers = cloud_config['datacenters'] + self.current_data_center = self.data_centers[self.current_context['datacenterName']] + self.auth_info = cloud_config['authInfos'][self.current_context['authInfoName']] + self.ssl_options = {} + self.skip_tls_verify = self.current_data_center.get('insecureSkipTlsVerify', False) + self.ssl_context = self.create_pyopenssl_context() if pyopenssl else self.create_ssl_context() + + proxy_address, port, node_domain = self.get_server(self.current_data_center) + + if not endpoint_factory: + endpoint_factory = SniEndPointFactory(proxy_address, port=int(port), node_domain=node_domain) + else: + assert isinstance(endpoint_factory, SniEndPointFactory) + self.endpoint_factory = endpoint_factory + + username, password = self.auth_info.get('username'), self.auth_info.get('password') + if username and password: + self.auth_provider = PlainTextAuthProvider(username, password) + + @property + def contact_points(self): + _contact_points = [] + for data_center in self.data_centers.values(): + _, _, node_domain = self.get_server(data_center) + _contact_points.append(self.endpoint_factory.create_from_sni(node_domain)) + return _contact_points + + def get_server(self, data_center): + address = data_center.get('server') + address = address.split(":") + port = nth(address, 1, default=9142) + address = nth(address, 0) + node_domain = data_center.get('nodeDomain') + assert address and port and node_domain, "server or nodeDomain are missing" + return address, port, node_domain + + def create_ssl_context(self): + ssl_context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT) + ssl_context.verify_mode = ssl.CERT_NONE if self.skip_tls_verify else ssl.CERT_REQUIRED + for data_center in self.data_centers.values(): + with file_or_memory(path=data_center.get('certificateAuthorityPath'), + data=data_center.get('certificateAuthorityData')) as cafile: + ssl_context.load_verify_locations(cadata=open(cafile).read()) + with file_or_memory(path=self.auth_info.get('clientCertificatePath'), + data=self.auth_info.get('clientCertificateData')) as certfile, \ + file_or_memory(path=self.auth_info.get('clientKeyPath'), data=self.auth_info.get('clientKeyData')) as keyfile: + ssl_context.load_cert_chain(keyfile=keyfile, + certfile=certfile) + + return ssl_context + + def create_pyopenssl_context(self): + try: + from OpenSSL import SSL + except ImportError as e: + raise ImportError( + "PyOpenSSL must be installed to connect to scylla-cloud with the Eventlet or Twisted event loops") \ + .with_traceback(e.__traceback__) + ssl_context = SSL.Context(SSL.TLS_METHOD) + ssl_context.set_verify(SSL.VERIFY_PEER, callback=lambda _1, _2, _3, _4, ok: True if self.skip_tls_verify else ok) + for data_center in self.data_centers.values(): + with file_or_memory(path=data_center.get('certificateAuthorityPath'), + data=data_center.get('certificateAuthorityData')) as cafile: + ssl_context.load_verify_locations(cafile) + with file_or_memory(path=self.auth_info.get('clientCertificatePath'), + data=self.auth_info.get('clientCertificateData')) as certfile, \ + file_or_memory(path=self.auth_info.get('clientKeyPath'), data=self.auth_info.get('clientKeyData')) as keyfile: + ssl_context.use_privatekey_file(keyfile) + ssl_context.use_certificate_file(certfile) + + return ssl_context + + @classmethod + def create(cls, configuration_file, pyopenssl=False, endpoint_factory=None): + return cls(configuration_file, pyopenssl=pyopenssl, endpoint_factory=endpoint_factory) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a159a6558286565f33fceb2cfe674dbd9c1adacf Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/_imp_emulation.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/_imp_emulation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f97674dcc97e65f01a455f76a48ee7304fad2a6d Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/_imp_emulation.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/_shimmed_dist_utils.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/_shimmed_dist_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62b67ec875737df74b412725c4a2d6771aae9cfc Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/_shimmed_dist_utils.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/api.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/api.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d9548800d11e5c1cb6406d28650befe95e8fa5d Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/api.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/backend_ctypes.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/backend_ctypes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03500aa18b2ae6893c217e4c103ad3638925e546 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/backend_ctypes.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/cffi_opcode.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/cffi_opcode.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ff23c7830d7e971d57c111438f2a5ed4422dcd6 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/cffi_opcode.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/commontypes.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/commontypes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7433af6321cc7e8b446622aa62eb77b6b0b1ebfc Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/commontypes.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/cparser.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/cparser.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19edf6946d2ceb668725d685f9286387e316a44c Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/cparser.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/error.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..987f67ad42cfaf4bd2fa18b34dbf77e33a6ea238 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/error.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/ffiplatform.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/ffiplatform.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..824385ae350d11f5671d9562a5d26d97eb7c8731 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/ffiplatform.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/lock.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/lock.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..095dc5d09c3ba958cef54105873125d073a868fb Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/lock.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/model.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97d6a1a6705c8b2b7b99c3dae16f15f3f8f0dbf8 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/model.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/pkgconfig.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/pkgconfig.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41da75ac98d9eeb91c5a1772c2ae571e309fd850 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/pkgconfig.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/recompiler.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/recompiler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6861fc6c447ec5b1a80d095ae147749fa3af488 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/recompiler.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/setuptools_ext.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/setuptools_ext.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc9f12b2a4eab9085aeb88bd0b602b0a35ea9e40 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/setuptools_ext.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/vengine_cpy.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/vengine_cpy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c442b0ab6a8b873708343e0a28f03687d14b4476 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/vengine_cpy.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/vengine_gen.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/vengine_gen.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca1a5bd4182e64ceca2432a1e1ef87cdd296b7ed Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/vengine_gen.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/verifier.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/verifier.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5e221e311bcb93ec454d1ec434c22405a309d81 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cffi/__pycache__/verifier.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b1d66d3b6806461cb5baed570737ffa8577aa7b Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/__pycache__/_common.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/__pycache__/_common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ef84327738396362d14f1a51381f23ec13919ca Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/__pycache__/_common.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/__pycache__/_version.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/__pycache__/_version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa49458738336810a97a0f3fb668f61eeabc8134 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/__pycache__/_version.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/__pycache__/easter.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/__pycache__/easter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f9e46e8a8def6101a82859465c5305a45e1f2ba Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/__pycache__/easter.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/__pycache__/relativedelta.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/__pycache__/relativedelta.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a5f734c0783d4fa869e9d4153b18ddce8ed9acb Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/__pycache__/relativedelta.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/__pycache__/rrule.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/__pycache__/rrule.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94f6f905c8b16c135445ac543761c5d76887f52e Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/__pycache__/rrule.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/__pycache__/tzwin.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/__pycache__/tzwin.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6544e166711087d2ea9e735fafe4dfbd9ecc80ab Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/__pycache__/tzwin.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/__pycache__/utils.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb26761706b63607d37380625153e9cb1493ddad Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/__pycache__/utils.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/parser/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/parser/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e07c819949763e4e56197f0379c5336619e72eb6 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/parser/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/parser/__pycache__/_parser.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/parser/__pycache__/_parser.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f100d838341cdc9f7cca2f439a22dc1f62d2fa4e Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/parser/__pycache__/_parser.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/parser/__pycache__/isoparser.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/parser/__pycache__/isoparser.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58cc09e2f8cf73f6d0951e4f6fc93c3d78b54116 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/parser/__pycache__/isoparser.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/tz/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/tz/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d3dc91dfe042b61dbeb71b92b1bb6e48988d7d3 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/tz/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/tz/__pycache__/_common.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/tz/__pycache__/_common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18ef7318d21ccffb18588fb43c9b25e6fcf9a7f3 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/tz/__pycache__/_common.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/tz/__pycache__/_factories.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/tz/__pycache__/_factories.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84bc7d43dc2617d9946c2a7653c3319a7fffef5a Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/tz/__pycache__/_factories.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/tz/__pycache__/tz.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/tz/__pycache__/tz.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19f5c755ee4571fce6b233aced556a2591f77a08 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/tz/__pycache__/tz.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/tz/__pycache__/win.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/tz/__pycache__/win.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a1b8396ad93d6ad2f03267cc7ef90af06303287 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/tz/__pycache__/win.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/zoneinfo/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/zoneinfo/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..130d775eb3ec7fc970765cb09ce729acea32a2de Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/zoneinfo/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/zoneinfo/__pycache__/rebuild.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/zoneinfo/__pycache__/rebuild.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7dd0ae09830b43db11bce559360fc126e2792604 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/zoneinfo/__pycache__/rebuild.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/zoneinfo/rebuild.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/zoneinfo/rebuild.py new file mode 100644 index 0000000000000000000000000000000000000000..684c6586f091350c347f2b6150935f5214ffec27 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/dateutil/zoneinfo/rebuild.py @@ -0,0 +1,75 @@ +import logging +import os +import tempfile +import shutil +import json +from subprocess import check_call, check_output +from tarfile import TarFile + +from dateutil.zoneinfo import METADATA_FN, ZONEFILENAME + + +def rebuild(filename, tag=None, format="gz", zonegroups=[], metadata=None): + """Rebuild the internal timezone info in dateutil/zoneinfo/zoneinfo*tar* + + filename is the timezone tarball from ``ftp.iana.org/tz``. + + """ + tmpdir = tempfile.mkdtemp() + zonedir = os.path.join(tmpdir, "zoneinfo") + moduledir = os.path.dirname(__file__) + try: + with TarFile.open(filename) as tf: + for name in zonegroups: + tf.extract(name, tmpdir) + filepaths = [os.path.join(tmpdir, n) for n in zonegroups] + + _run_zic(zonedir, filepaths) + + # write metadata file + with open(os.path.join(zonedir, METADATA_FN), 'w') as f: + json.dump(metadata, f, indent=4, sort_keys=True) + target = os.path.join(moduledir, ZONEFILENAME) + with TarFile.open(target, "w:%s" % format) as tf: + for entry in os.listdir(zonedir): + entrypath = os.path.join(zonedir, entry) + tf.add(entrypath, entry) + finally: + shutil.rmtree(tmpdir) + + +def _run_zic(zonedir, filepaths): + """Calls the ``zic`` compiler in a compatible way to get a "fat" binary. + + Recent versions of ``zic`` default to ``-b slim``, while older versions + don't even have the ``-b`` option (but default to "fat" binaries). The + current version of dateutil does not support Version 2+ TZif files, which + causes problems when used in conjunction with "slim" binaries, so this + function is used to ensure that we always get a "fat" binary. + """ + + try: + help_text = check_output(["zic", "--help"]) + except OSError as e: + _print_on_nosuchfile(e) + raise + + if b"-b " in help_text: + bloat_args = ["-b", "fat"] + else: + bloat_args = [] + + check_call(["zic"] + bloat_args + ["-d", zonedir] + filepaths) + + +def _print_on_nosuchfile(e): + """Print helpful troubleshooting message + + e is an exception raised by subprocess.check_call() + + """ + if e.errno == 2: + logging.error( + "Could not find zic. Perhaps you need to install " + "libc-bin or some other package that provides it, " + "or it's not in your PATH?") diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/geomet/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/geomet/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63fcb864332f951be64f091c9cd0ea7d3f517279 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/geomet/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/geomet/__pycache__/esri.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/geomet/__pycache__/esri.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..525a073ec01da9800f051e7339a4988ffd27a2e5 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/geomet/__pycache__/esri.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/geomet/__pycache__/geopackage.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/geomet/__pycache__/geopackage.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e05e1dc42bce8386f59738167b5479c17e7abb2c Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/geomet/__pycache__/geopackage.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/geomet/__pycache__/tool.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/geomet/__pycache__/tool.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eaba0a5a03b718991b970855967af67944030aa0 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/geomet/__pycache__/tool.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/geomet/__pycache__/util.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/geomet/__pycache__/util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03fca60538adc09723f16f68141ce4bb0475deec Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/geomet/__pycache__/util.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/geomet/__pycache__/wkb.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/geomet/__pycache__/wkb.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab14e0aaf598299592298adbba159e10e14adf1d Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/geomet/__pycache__/wkb.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/geomet/__pycache__/wkt.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/geomet/__pycache__/wkt.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d53d3763d6cb4b9864bc3f5887d76159ee20127 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/geomet/__pycache__/wkt.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2-3.1.6.dist-info/licenses/LICENSE.txt b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2-3.1.6.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..c37cae49ec77ad6ebb25568c1605f1fee5313cfb --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2-3.1.6.dist-info/licenses/LICENSE.txt @@ -0,0 +1,28 @@ +Copyright 2007 Pallets + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8943f6c46f5cca48daa5f678b94430292394359 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/_identifier.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/_identifier.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4eeeea2715c5be4891e637d51636bf0dd34a01f Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/_identifier.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/async_utils.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/async_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bad1cd35d0e1d95a6767579a6ffe2a99fe474791 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/async_utils.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/bccache.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/bccache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68da294584fb2ab3f634e5053e744c01ed68f8f9 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/bccache.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/compiler.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/compiler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63720465f73372db459c82e0c62438c9ab979227 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/compiler.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:def3cda409ab6455c767dabe32ae052d109cedee2b20597195f64bcc5f35519f +size 104061 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/constants.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/constants.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2931afb3e329b142f58c72559c7720efe6ae79b Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/constants.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/debug.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/debug.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35bff52c9d3ad603bbe7e4e8a758fe04d065448a Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/debug.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/defaults.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/defaults.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..036133cf4aca2b7a25a56336c06c3f9124d0e745 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/defaults.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/environment.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/environment.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87540d5e55469bd3c2186d2c1746949d5b50218d Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/environment.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/exceptions.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29782c9ef04bdcc6de962d65a11de1a4ee39047e Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/exceptions.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/ext.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/ext.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f36fe242178c6529a329ccb05e30597fa0f3c15e Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/ext.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/filters.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/filters.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bac9dbe69ae3696d318d008b8390e7c90283955a Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/filters.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/idtracking.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/idtracking.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbeff49a077608b45b703779d59da31d87369a9b Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/idtracking.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/lexer.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/lexer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81f16c5b6479ed1fa529556ecbc821bc8d862f2a Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/lexer.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/loaders.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/loaders.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ced424387043853e2ddb2ae2aa284f040b504367 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/loaders.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/meta.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/meta.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bdd8fc0c6c1403c129d71355a2d348e495277f27 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/meta.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/nativetypes.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/nativetypes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c82b1e93865bee6f98641ff71c46dfcf824de2c Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/nativetypes.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/nodes.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/nodes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8839f1b0a755dded90a54349fa460d04cd98af79 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/nodes.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/optimizer.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/optimizer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ee50e6b675e7a445385390bf27b33cdb77ed070 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/optimizer.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/parser.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/parser.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d9f1cd8cc3569669417dfeaff512abfb74e1b25 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/parser.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/runtime.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/runtime.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2391dada4d5d60b71dc666bec9d3c9490c0f383 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/runtime.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/sandbox.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/sandbox.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4dcb080f344ac063b90d84952f2dcc4b8c07ff9 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/sandbox.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/tests.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/tests.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..566ad3647643860ccfb37751f8d712704fafb4ed Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/tests.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/utils.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..789539ceb06c3a97631491a974aa7f63654d9414 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/utils.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/visitor.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/visitor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2616ae6df313173d24a8204bbe4d6263cbb22097 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/jinja2/__pycache__/visitor.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20f5df44a7cbd04e8a05113ea040f6ea64428b4a Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/_compat.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/_compat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54a7901bb65823a739651d89610acca1d5ffcb4e Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/_compat.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/_punycode.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/_punycode.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ecea662183c08d62ea6bf29b75b93c502e2f9e4 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/_punycode.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/main.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/main.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75599363b46cea12a1812001f8d491c8e7b58bef Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/main.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/parser_block.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/parser_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09212dfd794abcdc203578e7bc3d62cba54ccb87 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/parser_block.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/parser_core.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/parser_core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e406605d429b2f0baef35c779510dbc6d7aaa175 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/parser_core.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/parser_inline.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/parser_inline.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4fa08757fb7583a989e76d64341f896d73ff3378 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/parser_inline.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/renderer.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/renderer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ffc56e2b254c79e3c6d64e33b088d009b7e377a1 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/renderer.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/ruler.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/ruler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e58105f718023130edf151a9186c6367137ee33 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/ruler.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/token.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/token.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6778cf5261223f54f7bec3c84bb0260535cf5dd8 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/token.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/tree.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/tree.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f11162fde3e69ab31f54b88133c2476f7bfa0cf Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/tree.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/utils.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2ec389e691783b4de662dbb2921a115e33d6017 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/__pycache__/utils.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/cli/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/cli/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/cli/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1abd937f35eb0dd3b933d21c3a8fc1d023fdef4a Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/cli/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/cli/__pycache__/parse.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/cli/__pycache__/parse.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..676ff28c125e0327fda06250953749369fabeb75 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/cli/__pycache__/parse.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/cli/parse.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/cli/parse.py new file mode 100644 index 0000000000000000000000000000000000000000..fe346b2f51b055b62966c081139f9706e3295363 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/cli/parse.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python +""" +CLI interface to markdown-it-py + +Parse one or more markdown files, convert each to HTML, and print to stdout. +""" + +from __future__ import annotations + +import argparse +from collections.abc import Iterable, Sequence +import sys + +from markdown_it import __version__ +from markdown_it.main import MarkdownIt + +version_str = f"markdown-it-py [version {__version__}]" + + +def main(args: Sequence[str] | None = None) -> int: + namespace = parse_args(args) + if namespace.filenames: + convert(namespace.filenames) + else: + interactive() + return 0 + + +def convert(filenames: Iterable[str]) -> None: + for filename in filenames: + convert_file(filename) + + +def convert_file(filename: str) -> None: + """ + Parse a Markdown file and dump the output to stdout. + """ + try: + with open(filename, encoding="utf8", errors="ignore") as fin: + rendered = MarkdownIt().render(fin.read()) + print(rendered, end="") + except OSError: + sys.stderr.write(f'Cannot open file "{filename}".\n') + sys.exit(1) + + +def interactive() -> None: + """ + Parse user input, dump to stdout, rinse and repeat. + Python REPL style. + """ + print_heading() + contents = [] + more = False + while True: + try: + prompt, more = ("... ", True) if more else (">>> ", True) + contents.append(input(prompt) + "\n") + except EOFError: + print("\n" + MarkdownIt().render("\n".join(contents)), end="") + more = False + contents = [] + except KeyboardInterrupt: + print("\nExiting.") + break + + +def parse_args(args: Sequence[str] | None) -> argparse.Namespace: + """Parse input CLI arguments.""" + parser = argparse.ArgumentParser( + description="Parse one or more markdown files, " + "convert each to HTML, and print to stdout", + # NOTE: Remember to update README.md w/ the output of `markdown-it -h` + epilog=( + f""" +Interactive: + + $ markdown-it + markdown-it-py [version {__version__}] (interactive) + Type Ctrl-D to complete input, or Ctrl-C to exit. + >>> # Example + ... > markdown *input* + ... +

Example

+
+

markdown input

+
+ +Batch: + + $ markdown-it README.md README.footer.md > index.html +""" + ), + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + parser.add_argument("-v", "--version", action="version", version=version_str) + parser.add_argument( + "filenames", nargs="*", help="specify an optional list of files to convert" + ) + return parser.parse_args(args) + + +def print_heading() -> None: + print(f"{version_str} (interactive)") + print("Type Ctrl-D to complete input, or Ctrl-C to exit.") + + +if __name__ == "__main__": + exit_code = main(sys.argv[1:]) + sys.exit(exit_code) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e8c66e0e3e8c8b845dfaa5da702fba34147f6c2 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/__pycache__/entities.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/__pycache__/entities.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65cd81a0ed2e8f70ea34bfb5fe4368195a2c8b20 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/__pycache__/entities.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/__pycache__/html_blocks.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/__pycache__/html_blocks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9347673e77301e8f17aa36204c0890049c7885fe Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/__pycache__/html_blocks.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/__pycache__/html_re.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/__pycache__/html_re.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad06ede5fe1062c27b1926f425ca077a7ca704c4 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/__pycache__/html_re.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/__pycache__/normalize_url.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/__pycache__/normalize_url.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2969ff69c0592c65cbea0c67b6e294b0690cffc Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/__pycache__/normalize_url.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/__pycache__/utils.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..749c34f0daf12990ff7bb1bb49fc698b9815d58d Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/__pycache__/utils.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/entities.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/entities.py new file mode 100644 index 0000000000000000000000000000000000000000..14d08ec9546995f8eea3e9b83ea896f29ef020cb --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/entities.py @@ -0,0 +1,5 @@ +"""HTML5 entities map: { name -> characters }.""" + +import html.entities + +entities = {name.rstrip(";"): chars for name, chars in html.entities.html5.items()} diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/html_blocks.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/html_blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..8a3b0b7d5ab7bc174a3c96cbc8976816278a6c21 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/html_blocks.py @@ -0,0 +1,69 @@ +"""List of valid html blocks names, according to commonmark spec +http://jgm.github.io/CommonMark/spec.html#html-blocks +""" + +# see https://spec.commonmark.org/0.31.2/#html-blocks +block_names = [ + "address", + "article", + "aside", + "base", + "basefont", + "blockquote", + "body", + "caption", + "center", + "col", + "colgroup", + "dd", + "details", + "dialog", + "dir", + "div", + "dl", + "dt", + "fieldset", + "figcaption", + "figure", + "footer", + "form", + "frame", + "frameset", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "head", + "header", + "hr", + "html", + "iframe", + "legend", + "li", + "link", + "main", + "menu", + "menuitem", + "nav", + "noframes", + "ol", + "optgroup", + "option", + "p", + "param", + "search", + "section", + "summary", + "table", + "tbody", + "td", + "tfoot", + "th", + "thead", + "title", + "tr", + "track", + "ul", +] diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/html_re.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/html_re.py new file mode 100644 index 0000000000000000000000000000000000000000..ab822c5fc487c5a494966604a1e89b57a06e0564 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/html_re.py @@ -0,0 +1,39 @@ +"""Regexps to match html elements""" + +import re + +attr_name = "[a-zA-Z_:][a-zA-Z0-9:._-]*" + +unquoted = "[^\"'=<>`\\x00-\\x20]+" +single_quoted = "'[^']*'" +double_quoted = '"[^"]*"' + +attr_value = "(?:" + unquoted + "|" + single_quoted + "|" + double_quoted + ")" + +attribute = "(?:\\s+" + attr_name + "(?:\\s*=\\s*" + attr_value + ")?)" + +open_tag = "<[A-Za-z][A-Za-z0-9\\-]*" + attribute + "*\\s*\\/?>" + +close_tag = "<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>" +comment = "" +processing = "<[?][\\s\\S]*?[?]>" +declaration = "]*>" +cdata = "" + +HTML_TAG_RE = re.compile( + "^(?:" + + open_tag + + "|" + + close_tag + + "|" + + comment + + "|" + + processing + + "|" + + declaration + + "|" + + cdata + + ")" +) +HTML_OPEN_CLOSE_TAG_STR = "^(?:" + open_tag + "|" + close_tag + ")" +HTML_OPEN_CLOSE_TAG_RE = re.compile(HTML_OPEN_CLOSE_TAG_STR) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/normalize_url.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/normalize_url.py new file mode 100644 index 0000000000000000000000000000000000000000..92720b31621b0f6b4ac853179d886cb58e4e2f36 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/normalize_url.py @@ -0,0 +1,81 @@ +from __future__ import annotations + +from collections.abc import Callable +from contextlib import suppress +import re +from urllib.parse import quote, unquote, urlparse, urlunparse # noqa: F401 + +import mdurl + +from .. import _punycode + +RECODE_HOSTNAME_FOR = ("http:", "https:", "mailto:") + + +def normalizeLink(url: str) -> str: + """Normalize destination URLs in links + + :: + + [label]: destination 'title' + ^^^^^^^^^^^ + """ + parsed = mdurl.parse(url, slashes_denote_host=True) + + # Encode hostnames in urls like: + # `http://host/`, `https://host/`, `mailto:user@host`, `//host/` + # + # We don't encode unknown schemas, because it's likely that we encode + # something we shouldn't (e.g. `skype:name` treated as `skype:host`) + # + if parsed.hostname and ( + not parsed.protocol or parsed.protocol in RECODE_HOSTNAME_FOR + ): + with suppress(Exception): + parsed = parsed._replace(hostname=_punycode.to_ascii(parsed.hostname)) + + return mdurl.encode(mdurl.format(parsed)) + + +def normalizeLinkText(url: str) -> str: + """Normalize autolink content + + :: + + + ~~~~~~~~~~~ + """ + parsed = mdurl.parse(url, slashes_denote_host=True) + + # Encode hostnames in urls like: + # `http://host/`, `https://host/`, `mailto:user@host`, `//host/` + # + # We don't encode unknown schemas, because it's likely that we encode + # something we shouldn't (e.g. `skype:name` treated as `skype:host`) + # + if parsed.hostname and ( + not parsed.protocol or parsed.protocol in RECODE_HOSTNAME_FOR + ): + with suppress(Exception): + parsed = parsed._replace(hostname=_punycode.to_unicode(parsed.hostname)) + + # add '%' to exclude list because of https://github.com/markdown-it/markdown-it/issues/720 + return mdurl.decode(mdurl.format(parsed), mdurl.DECODE_DEFAULT_CHARS + "%") + + +BAD_PROTO_RE = re.compile(r"^(vbscript|javascript|file|data):") +GOOD_DATA_RE = re.compile(r"^data:image\/(gif|png|jpeg|webp);") + + +def validateLink(url: str, validator: Callable[[str], bool] | None = None) -> bool: + """Validate URL link is allowed in output. + + This validator can prohibit more than really needed to prevent XSS. + It's a tradeoff to keep code simple and to be secure by default. + + Note: url should be normalized at this point, and existing entities decoded. + """ + if validator is not None: + return validator(url) + url = url.strip().lower() + return bool(GOOD_DATA_RE.search(url)) if BAD_PROTO_RE.search(url) else True diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/utils.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..11bda644c260b714cf010ed44d2ed345de80314e --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/common/utils.py @@ -0,0 +1,313 @@ +"""Utilities for parsing source text""" + +from __future__ import annotations + +import re +from re import Match +from typing import TypeVar +import unicodedata + +from .entities import entities + + +def charCodeAt(src: str, pos: int) -> int | None: + """ + Returns the Unicode value of the character at the specified location. + + @param - index The zero-based index of the desired character. + If there is no character at the specified index, NaN is returned. + + This was added for compatibility with python + """ + try: + return ord(src[pos]) + except IndexError: + return None + + +def charStrAt(src: str, pos: int) -> str | None: + """ + Returns the Unicode value of the character at the specified location. + + @param - index The zero-based index of the desired character. + If there is no character at the specified index, NaN is returned. + + This was added for compatibility with python + """ + try: + return src[pos] + except IndexError: + return None + + +_ItemTV = TypeVar("_ItemTV") + + +def arrayReplaceAt( + src: list[_ItemTV], pos: int, newElements: list[_ItemTV] +) -> list[_ItemTV]: + """ + Remove element from array and put another array at those position. + Useful for some operations with tokens + """ + return src[:pos] + newElements + src[pos + 1 :] + + +def isValidEntityCode(c: int) -> bool: + # broken sequence + if c >= 0xD800 and c <= 0xDFFF: + return False + # never used + if c >= 0xFDD0 and c <= 0xFDEF: + return False + if ((c & 0xFFFF) == 0xFFFF) or ((c & 0xFFFF) == 0xFFFE): + return False + # control codes + if c >= 0x00 and c <= 0x08: + return False + if c == 0x0B: + return False + if c >= 0x0E and c <= 0x1F: + return False + if c >= 0x7F and c <= 0x9F: + return False + # out of range + return not (c > 0x10FFFF) + + +def fromCodePoint(c: int) -> str: + """Convert ordinal to unicode. + + Note, in the original Javascript two string characters were required, + for codepoints larger than `0xFFFF`. + But Python 3 can represent any unicode codepoint in one character. + """ + return chr(c) + + +# UNESCAPE_MD_RE = re.compile(r'\\([!"#$%&\'()*+,\-.\/:;<=>?@[\\\]^_`{|}~])') +# ENTITY_RE_g = re.compile(r'&([a-z#][a-z0-9]{1,31})', re.IGNORECASE) +UNESCAPE_ALL_RE = re.compile( + r'\\([!"#$%&\'()*+,\-.\/:;<=>?@[\\\]^_`{|}~])' + "|" + r"&([a-z#][a-z0-9]{1,31});", + re.IGNORECASE, +) +DIGITAL_ENTITY_BASE10_RE = re.compile(r"#([0-9]{1,8})") +DIGITAL_ENTITY_BASE16_RE = re.compile(r"#x([a-f0-9]{1,8})", re.IGNORECASE) + + +def replaceEntityPattern(match: str, name: str) -> str: + """Convert HTML entity patterns, + see https://spec.commonmark.org/0.30/#entity-references + """ + if name in entities: + return entities[name] + + code: None | int = None + if pat := DIGITAL_ENTITY_BASE10_RE.fullmatch(name): + code = int(pat.group(1), 10) + elif pat := DIGITAL_ENTITY_BASE16_RE.fullmatch(name): + code = int(pat.group(1), 16) + + if code is not None and isValidEntityCode(code): + return fromCodePoint(code) + + return match + + +def unescapeAll(string: str) -> str: + def replacer_func(match: Match[str]) -> str: + escaped = match.group(1) + if escaped: + return escaped + entity = match.group(2) + return replaceEntityPattern(match.group(), entity) + + if "\\" not in string and "&" not in string: + return string + return UNESCAPE_ALL_RE.sub(replacer_func, string) + + +ESCAPABLE = r"""\\!"#$%&'()*+,./:;<=>?@\[\]^`{}|_~-""" +ESCAPE_CHAR = re.compile(r"\\([" + ESCAPABLE + r"])") + + +def stripEscape(string: str) -> str: + """Strip escape \\ characters""" + return ESCAPE_CHAR.sub(r"\1", string) + + +def escapeHtml(raw: str) -> str: + """Replace special characters "&", "<", ">" and '"' to HTML-safe sequences.""" + # like html.escape, but without escaping single quotes + raw = raw.replace("&", "&") # Must be done first! + raw = raw.replace("<", "<") + raw = raw.replace(">", ">") + raw = raw.replace('"', """) + return raw + + +# ////////////////////////////////////////////////////////////////////////////// + +REGEXP_ESCAPE_RE = re.compile(r"[.?*+^$[\]\\(){}|-]") + + +def escapeRE(string: str) -> str: + string = REGEXP_ESCAPE_RE.sub("\\$&", string) + return string + + +# ////////////////////////////////////////////////////////////////////////////// + + +def isSpace(code: int | None) -> bool: + """Check if character code is a whitespace.""" + return code in (0x09, 0x20) + + +def isStrSpace(ch: str | None) -> bool: + """Check if character is a whitespace.""" + return ch in ("\t", " ") + + +MD_WHITESPACE = { + 0x09, # \t + 0x0A, # \n + 0x0B, # \v + 0x0C, # \f + 0x0D, # \r + 0x20, # space + 0xA0, + 0x1680, + 0x202F, + 0x205F, + 0x3000, +} + + +def isWhiteSpace(code: int) -> bool: + r"""Zs (unicode class) || [\t\f\v\r\n]""" + if code >= 0x2000 and code <= 0x200A: + return True + return code in MD_WHITESPACE + + +# ////////////////////////////////////////////////////////////////////////////// + + +def isPunctChar(ch: str) -> bool: + """Check if character is a punctuation character.""" + return unicodedata.category(ch).startswith(("P", "S")) + + +MD_ASCII_PUNCT = { + 0x21, # /* ! */ + 0x22, # /* " */ + 0x23, # /* # */ + 0x24, # /* $ */ + 0x25, # /* % */ + 0x26, # /* & */ + 0x27, # /* ' */ + 0x28, # /* ( */ + 0x29, # /* ) */ + 0x2A, # /* * */ + 0x2B, # /* + */ + 0x2C, # /* , */ + 0x2D, # /* - */ + 0x2E, # /* . */ + 0x2F, # /* / */ + 0x3A, # /* : */ + 0x3B, # /* ; */ + 0x3C, # /* < */ + 0x3D, # /* = */ + 0x3E, # /* > */ + 0x3F, # /* ? */ + 0x40, # /* @ */ + 0x5B, # /* [ */ + 0x5C, # /* \ */ + 0x5D, # /* ] */ + 0x5E, # /* ^ */ + 0x5F, # /* _ */ + 0x60, # /* ` */ + 0x7B, # /* { */ + 0x7C, # /* | */ + 0x7D, # /* } */ + 0x7E, # /* ~ */ +} + + +def isMdAsciiPunct(ch: int) -> bool: + """Markdown ASCII punctuation characters. + + :: + + !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \\, ], ^, _, `, {, |, }, or ~ + + See http://spec.commonmark.org/0.15/#ascii-punctuation-character + + Don't confuse with unicode punctuation !!! It lacks some chars in ascii range. + + """ + return ch in MD_ASCII_PUNCT + + +def normalizeReference(string: str) -> str: + """Helper to unify [reference labels].""" + # Trim and collapse whitespace + # + string = re.sub(r"\s+", " ", string.strip()) + + # In node v10 'ẞ'.toLowerCase() === 'Ṿ', which is presumed to be a bug + # fixed in v12 (couldn't find any details). + # + # So treat this one as a special case + # (remove this when node v10 is no longer supported). + # + # if ('ẞ'.toLowerCase() === 'Ṿ') { + # str = str.replace(/ẞ/g, 'ß') + # } + + # .toLowerCase().toUpperCase() should get rid of all differences + # between letter variants. + # + # Simple .toLowerCase() doesn't normalize 125 code points correctly, + # and .toUpperCase doesn't normalize 6 of them (list of exceptions: + # İ, ϴ, ẞ, Ω, K, Å - those are already uppercased, but have differently + # uppercased versions). + # + # Here's an example showing how it happens. Lets take greek letter omega: + # uppercase U+0398 (Θ), U+03f4 (ϴ) and lowercase U+03b8 (θ), U+03d1 (ϑ) + # + # Unicode entries: + # 0398;GREEK CAPITAL LETTER THETA;Lu;0;L;;;;;N;;;;03B8 + # 03B8;GREEK SMALL LETTER THETA;Ll;0;L;;;;;N;;;0398;;0398 + # 03D1;GREEK THETA SYMBOL;Ll;0;L; 03B8;;;;N;GREEK SMALL LETTER SCRIPT THETA;;0398;;0398 + # 03F4;GREEK CAPITAL THETA SYMBOL;Lu;0;L; 0398;;;;N;;;;03B8 + # + # Case-insensitive comparison should treat all of them as equivalent. + # + # But .toLowerCase() doesn't change ϑ (it's already lowercase), + # and .toUpperCase() doesn't change ϴ (already uppercase). + # + # Applying first lower then upper case normalizes any character: + # '\u0398\u03f4\u03b8\u03d1'.toLowerCase().toUpperCase() === '\u0398\u0398\u0398\u0398' + # + # Note: this is equivalent to unicode case folding; unicode normalization + # is a different step that is not required here. + # + # Final result should be uppercased, because it's later stored in an object + # (this avoid a conflict with Object.prototype members, + # most notably, `__proto__`) + # + return string.lower().upper() + + +LINK_OPEN_RE = re.compile(r"^\s]", flags=re.IGNORECASE) +LINK_CLOSE_RE = re.compile(r"^", flags=re.IGNORECASE) + + +def isLinkOpen(string: str) -> bool: + return bool(LINK_OPEN_RE.search(string)) + + +def isLinkClose(string: str) -> bool: + return bool(LINK_CLOSE_RE.search(string)) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/helpers/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/helpers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f4e2cd21b94b9ee9ecb0cac21da619233a5258b9 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/helpers/__init__.py @@ -0,0 +1,6 @@ +"""Functions for parsing Links""" + +__all__ = ("parseLinkDestination", "parseLinkLabel", "parseLinkTitle") +from .parse_link_destination import parseLinkDestination +from .parse_link_label import parseLinkLabel +from .parse_link_title import parseLinkTitle diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/helpers/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/helpers/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..038f2f1a703aeef38188d5b2eb7b49870d9da139 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/helpers/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/helpers/__pycache__/parse_link_destination.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/helpers/__pycache__/parse_link_destination.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..730110d44952b349b72c65122808f3e212f6cc04 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/helpers/__pycache__/parse_link_destination.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/helpers/__pycache__/parse_link_label.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/helpers/__pycache__/parse_link_label.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..855b03c292f14ca2e24b1fa1419be3292befee6d Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/helpers/__pycache__/parse_link_label.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/helpers/__pycache__/parse_link_title.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/helpers/__pycache__/parse_link_title.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..475d47dca1bd541965d08848bb97748c4ad32830 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/helpers/__pycache__/parse_link_title.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/helpers/parse_link_destination.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/helpers/parse_link_destination.py new file mode 100644 index 0000000000000000000000000000000000000000..c98323c056e0103a12849671fbbac58dc76de4b4 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/helpers/parse_link_destination.py @@ -0,0 +1,83 @@ +""" +Parse link destination +""" + +from ..common.utils import charCodeAt, unescapeAll + + +class _Result: + __slots__ = ("ok", "pos", "str") + + def __init__(self) -> None: + self.ok = False + self.pos = 0 + self.str = "" + + +def parseLinkDestination(string: str, pos: int, maximum: int) -> _Result: + start = pos + result = _Result() + + if charCodeAt(string, pos) == 0x3C: # /* < */ + pos += 1 + while pos < maximum: + code = charCodeAt(string, pos) + if code == 0x0A: # /* \n */) + return result + if code == 0x3C: # / * < * / + return result + if code == 0x3E: # /* > */) { + result.pos = pos + 1 + result.str = unescapeAll(string[start + 1 : pos]) + result.ok = True + return result + + if code == 0x5C and pos + 1 < maximum: # \ + pos += 2 + continue + + pos += 1 + + # no closing '>' + return result + + # this should be ... } else { ... branch + + level = 0 + while pos < maximum: + code = charCodeAt(string, pos) + + if code is None or code == 0x20: + break + + # ascii control characters + if code < 0x20 or code == 0x7F: + break + + if code == 0x5C and pos + 1 < maximum: + if charCodeAt(string, pos + 1) == 0x20: + break + pos += 2 + continue + + if code == 0x28: # /* ( */) + level += 1 + if level > 32: + return result + + if code == 0x29: # /* ) */) + if level == 0: + break + level -= 1 + + pos += 1 + + if start == pos: + return result + if level != 0: + return result + + result.str = unescapeAll(string[start:pos]) + result.pos = pos + result.ok = True + return result diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/helpers/parse_link_label.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/helpers/parse_link_label.py new file mode 100644 index 0000000000000000000000000000000000000000..c80da5a7ec54521281dac45b66977404f5384491 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/helpers/parse_link_label.py @@ -0,0 +1,44 @@ +""" +Parse link label + +this function assumes that first character ("[") already matches +returns the end of the label + +""" + +from markdown_it.rules_inline import StateInline + + +def parseLinkLabel(state: StateInline, start: int, disableNested: bool = False) -> int: + labelEnd = -1 + oldPos = state.pos + found = False + + state.pos = start + 1 + level = 1 + + while state.pos < state.posMax: + marker = state.src[state.pos] + if marker == "]": + level -= 1 + if level == 0: + found = True + break + + prevPos = state.pos + state.md.inline.skipToken(state) + if marker == "[": + if prevPos == state.pos - 1: + # increase level if we find text `[`, + # which is not a part of any token + level += 1 + elif disableNested: + state.pos = oldPos + return -1 + if found: + labelEnd = state.pos + + # restore old state + state.pos = oldPos + + return labelEnd diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/helpers/parse_link_title.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/helpers/parse_link_title.py new file mode 100644 index 0000000000000000000000000000000000000000..a38ff0d98ac7feaba80fd67f3c8f0d0454dde47f --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/helpers/parse_link_title.py @@ -0,0 +1,75 @@ +"""Parse link title""" + +from ..common.utils import charCodeAt, unescapeAll + + +class _State: + __slots__ = ("can_continue", "marker", "ok", "pos", "str") + + def __init__(self) -> None: + self.ok = False + """if `true`, this is a valid link title""" + self.can_continue = False + """if `true`, this link can be continued on the next line""" + self.pos = 0 + """if `ok`, it's the position of the first character after the closing marker""" + self.str = "" + """if `ok`, it's the unescaped title""" + self.marker = 0 + """expected closing marker character code""" + + def __str__(self) -> str: + return self.str + + +def parseLinkTitle( + string: str, start: int, maximum: int, prev_state: _State | None = None +) -> _State: + """Parse link title within `str` in [start, max] range, + or continue previous parsing if `prev_state` is defined (equal to result of last execution). + """ + pos = start + state = _State() + + if prev_state is not None: + # this is a continuation of a previous parseLinkTitle call on the next line, + # used in reference links only + state.str = prev_state.str + state.marker = prev_state.marker + else: + if pos >= maximum: + return state + + marker = charCodeAt(string, pos) + + # /* " */ /* ' */ /* ( */ + if marker != 0x22 and marker != 0x27 and marker != 0x28: + return state + + start += 1 + pos += 1 + + # if opening marker is "(", switch it to closing marker ")" + if marker == 0x28: + marker = 0x29 + + state.marker = marker + + while pos < maximum: + code = charCodeAt(string, pos) + if code == state.marker: + state.pos = pos + 1 + state.str += unescapeAll(string[start:pos]) + state.ok = True + return state + elif code == 0x28 and state.marker == 0x29: # /* ( */ /* ) */ + return state + elif code == 0x5C and pos + 1 < maximum: # /* \ */ + pos += 1 + + pos += 1 + + # no closing marker found, but this link title may continue on the next line (for references) + state.can_continue = True + state.str += unescapeAll(string[start:pos]) + return state diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/presets/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/presets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e21c7806930223fc6a2fda250f1c3e4065ef8c8f --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/presets/__init__.py @@ -0,0 +1,28 @@ +__all__ = ("commonmark", "default", "gfm_like", "js_default", "zero") + +from ..utils import PresetType +from . import commonmark, default, zero + +js_default = default + + +class gfm_like: # noqa: N801 + """GitHub Flavoured Markdown (GFM) like. + + This adds the linkify, table and strikethrough components to CommmonMark. + + Note, it lacks task-list items and raw HTML filtering, + to meet the the full GFM specification + (see https://github.github.com/gfm/#autolinks-extension-). + """ + + @staticmethod + def make() -> PresetType: + config = commonmark.make() + config["components"]["core"]["rules"].append("linkify") + config["components"]["block"]["rules"].append("table") + config["components"]["inline"]["rules"].extend(["strikethrough", "linkify"]) + config["components"]["inline"]["rules2"].append("strikethrough") + config["options"]["linkify"] = True + config["options"]["html"] = True + return config diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/presets/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/presets/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..292fefef537f45380477f20e5f08ca18602b2272 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/presets/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/presets/__pycache__/commonmark.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/presets/__pycache__/commonmark.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1abf426371972ba6e07ff42dd0d6736b2b924086 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/presets/__pycache__/commonmark.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/presets/__pycache__/default.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/presets/__pycache__/default.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7375aad68b84ca0c491547710795d78b6e6b4258 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/presets/__pycache__/default.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/presets/__pycache__/zero.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/presets/__pycache__/zero.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c12f867a05ad9dce4a14837838cfe9d12586df5c Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/presets/__pycache__/zero.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/presets/commonmark.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/presets/commonmark.py new file mode 100644 index 0000000000000000000000000000000000000000..ed0de0fe4dfbad9e3ab82477433805ea0b6650c6 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/presets/commonmark.py @@ -0,0 +1,75 @@ +"""Commonmark default options. + +This differs to presets.default, +primarily in that it allows HTML and does not enable components: + +- block: table +- inline: strikethrough +""" + +from ..utils import PresetType + + +def make() -> PresetType: + return { + "options": { + "maxNesting": 20, # Internal protection, recursion limit + "html": True, # Enable HTML tags in source, + # this is just a shorthand for .enable(["html_inline", "html_block"]) + # used by the linkify rule: + "linkify": False, # autoconvert URL-like texts to links + # used by the replacements and smartquotes rules + # Enable some language-neutral replacements + quotes beautification + "typographer": False, + # used by the smartquotes rule: + # Double + single quotes replacement pairs, when typographer enabled, + # and smartquotes on. Could be either a String or an Array. + # + # For example, you can use '«»„“' for Russian, '„“‚‘' for German, + # and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). + "quotes": "\u201c\u201d\u2018\u2019", # /* “”‘’ */ + # Renderer specific; these options are used directly in the HTML renderer + "xhtmlOut": True, # Use '/' to close single tags (
) + "breaks": False, # Convert '\n' in paragraphs into
+ "langPrefix": "language-", # CSS language prefix for fenced blocks + # Highlighter function. Should return escaped HTML, + # or '' if the source string is not changed and should be escaped externally. + # If result starts with PresetType: + return { + "options": { + "maxNesting": 100, # Internal protection, recursion limit + "html": False, # Enable HTML tags in source + # this is just a shorthand for .disable(["html_inline", "html_block"]) + # used by the linkify rule: + "linkify": False, # autoconvert URL-like texts to links + # used by the replacements and smartquotes rules: + # Enable some language-neutral replacements + quotes beautification + "typographer": False, + # used by the smartquotes rule: + # Double + single quotes replacement pairs, when typographer enabled, + # and smartquotes on. Could be either a String or an Array. + # For example, you can use '«»„“' for Russian, '„“‚‘' for German, + # and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). + "quotes": "\u201c\u201d\u2018\u2019", # /* “”‘’ */ + # Renderer specific; these options are used directly in the HTML renderer + "xhtmlOut": False, # Use '/' to close single tags (
) + "breaks": False, # Convert '\n' in paragraphs into
+ "langPrefix": "language-", # CSS language prefix for fenced blocks + # Highlighter function. Should return escaped HTML, + # or '' if the source string is not changed and should be escaped externally. + # If result starts with PresetType: + return { + "options": { + "maxNesting": 20, # Internal protection, recursion limit + "html": False, # Enable HTML tags in source + # this is just a shorthand for .disable(["html_inline", "html_block"]) + # used by the linkify rule: + "linkify": False, # autoconvert URL-like texts to links + # used by the replacements and smartquotes rules: + # Enable some language-neutral replacements + quotes beautification + "typographer": False, + # used by the smartquotes rule: + # Double + single quotes replacement pairs, when typographer enabled, + # and smartquotes on. Could be either a String or an Array. + # For example, you can use '«»„“' for Russian, '„“‚‘' for German, + # and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). + "quotes": "\u201c\u201d\u2018\u2019", # /* “”‘’ */ + # Renderer specific; these options are used directly in the HTML renderer + "xhtmlOut": False, # Use '/' to close single tags (
) + "breaks": False, # Convert '\n' in paragraphs into
+ "langPrefix": "language-", # CSS language prefix for fenced blocks + # Highlighter function. Should return escaped HTML, + # or '' if the source string is not changed and should be escaped externally. + # If result starts with bool: + LOGGER.debug( + "entering blockquote: %s, %s, %s, %s", state, startLine, endLine, silent + ) + + oldLineMax = state.lineMax + pos = state.bMarks[startLine] + state.tShift[startLine] + max = state.eMarks[startLine] + + if state.is_code_block(startLine): + return False + + # check the block quote marker + try: + if state.src[pos] != ">": + return False + except IndexError: + return False + pos += 1 + + # we know that it's going to be a valid blockquote, + # so no point trying to find the end of it in silent mode + if silent: + return True + + # set offset past spaces and ">" + initial = offset = state.sCount[startLine] + 1 + + try: + second_char: str | None = state.src[pos] + except IndexError: + second_char = None + + # skip one optional space after '>' + if second_char == " ": + # ' > test ' + # ^ -- position start of line here: + pos += 1 + initial += 1 + offset += 1 + adjustTab = False + spaceAfterMarker = True + elif second_char == "\t": + spaceAfterMarker = True + + if (state.bsCount[startLine] + offset) % 4 == 3: + # ' >\t test ' + # ^ -- position start of line here (tab has width==1) + pos += 1 + initial += 1 + offset += 1 + adjustTab = False + else: + # ' >\t test ' + # ^ -- position start of line here + shift bsCount slightly + # to make extra space appear + adjustTab = True + + else: + spaceAfterMarker = False + + oldBMarks = [state.bMarks[startLine]] + state.bMarks[startLine] = pos + + while pos < max: + ch = state.src[pos] + + if isStrSpace(ch): + if ch == "\t": + offset += ( + 4 + - (offset + state.bsCount[startLine] + (1 if adjustTab else 0)) % 4 + ) + else: + offset += 1 + + else: + break + + pos += 1 + + oldBSCount = [state.bsCount[startLine]] + state.bsCount[startLine] = ( + state.sCount[startLine] + 1 + (1 if spaceAfterMarker else 0) + ) + + lastLineEmpty = pos >= max + + oldSCount = [state.sCount[startLine]] + state.sCount[startLine] = offset - initial + + oldTShift = [state.tShift[startLine]] + state.tShift[startLine] = pos - state.bMarks[startLine] + + terminatorRules = state.md.block.ruler.getRules("blockquote") + + oldParentType = state.parentType + state.parentType = "blockquote" + + # Search the end of the block + # + # Block ends with either: + # 1. an empty line outside: + # ``` + # > test + # + # ``` + # 2. an empty line inside: + # ``` + # > + # test + # ``` + # 3. another tag: + # ``` + # > test + # - - - + # ``` + + # for (nextLine = startLine + 1; nextLine < endLine; nextLine++) { + nextLine = startLine + 1 + while nextLine < endLine: + # check if it's outdented, i.e. it's inside list item and indented + # less than said list item: + # + # ``` + # 1. anything + # > current blockquote + # 2. checking this line + # ``` + isOutdented = state.sCount[nextLine] < state.blkIndent + + pos = state.bMarks[nextLine] + state.tShift[nextLine] + max = state.eMarks[nextLine] + + if pos >= max: + # Case 1: line is not inside the blockquote, and this line is empty. + break + + evaluatesTrue = state.src[pos] == ">" and not isOutdented + pos += 1 + if evaluatesTrue: + # This line is inside the blockquote. + + # set offset past spaces and ">" + initial = offset = state.sCount[nextLine] + 1 + + try: + next_char: str | None = state.src[pos] + except IndexError: + next_char = None + + # skip one optional space after '>' + if next_char == " ": + # ' > test ' + # ^ -- position start of line here: + pos += 1 + initial += 1 + offset += 1 + adjustTab = False + spaceAfterMarker = True + elif next_char == "\t": + spaceAfterMarker = True + + if (state.bsCount[nextLine] + offset) % 4 == 3: + # ' >\t test ' + # ^ -- position start of line here (tab has width==1) + pos += 1 + initial += 1 + offset += 1 + adjustTab = False + else: + # ' >\t test ' + # ^ -- position start of line here + shift bsCount slightly + # to make extra space appear + adjustTab = True + + else: + spaceAfterMarker = False + + oldBMarks.append(state.bMarks[nextLine]) + state.bMarks[nextLine] = pos + + while pos < max: + ch = state.src[pos] + + if isStrSpace(ch): + if ch == "\t": + offset += ( + 4 + - ( + offset + + state.bsCount[nextLine] + + (1 if adjustTab else 0) + ) + % 4 + ) + else: + offset += 1 + else: + break + + pos += 1 + + lastLineEmpty = pos >= max + + oldBSCount.append(state.bsCount[nextLine]) + state.bsCount[nextLine] = ( + state.sCount[nextLine] + 1 + (1 if spaceAfterMarker else 0) + ) + + oldSCount.append(state.sCount[nextLine]) + state.sCount[nextLine] = offset - initial + + oldTShift.append(state.tShift[nextLine]) + state.tShift[nextLine] = pos - state.bMarks[nextLine] + + nextLine += 1 + continue + + # Case 2: line is not inside the blockquote, and the last line was empty. + if lastLineEmpty: + break + + # Case 3: another tag found. + terminate = False + + for terminatorRule in terminatorRules: + if terminatorRule(state, nextLine, endLine, True): + terminate = True + break + + if terminate: + # Quirk to enforce "hard termination mode" for paragraphs; + # normally if you call `tokenize(state, startLine, nextLine)`, + # paragraphs will look below nextLine for paragraph continuation, + # but if blockquote is terminated by another tag, they shouldn't + state.lineMax = nextLine + + if state.blkIndent != 0: + # state.blkIndent was non-zero, we now set it to zero, + # so we need to re-calculate all offsets to appear as + # if indent wasn't changed + oldBMarks.append(state.bMarks[nextLine]) + oldBSCount.append(state.bsCount[nextLine]) + oldTShift.append(state.tShift[nextLine]) + oldSCount.append(state.sCount[nextLine]) + state.sCount[nextLine] -= state.blkIndent + + break + + oldBMarks.append(state.bMarks[nextLine]) + oldBSCount.append(state.bsCount[nextLine]) + oldTShift.append(state.tShift[nextLine]) + oldSCount.append(state.sCount[nextLine]) + + # A negative indentation means that this is a paragraph continuation + # + state.sCount[nextLine] = -1 + + nextLine += 1 + + oldIndent = state.blkIndent + state.blkIndent = 0 + + token = state.push("blockquote_open", "blockquote", 1) + token.markup = ">" + token.map = lines = [startLine, 0] + + state.md.block.tokenize(state, startLine, nextLine) + + token = state.push("blockquote_close", "blockquote", -1) + token.markup = ">" + + state.lineMax = oldLineMax + state.parentType = oldParentType + lines[1] = state.line + + # Restore original tShift; this might not be necessary since the parser + # has already been here, but just to make sure we can do that. + for i, item in enumerate(oldTShift): + state.bMarks[i + startLine] = oldBMarks[i] + state.tShift[i + startLine] = item + state.sCount[i + startLine] = oldSCount[i] + state.bsCount[i + startLine] = oldBSCount[i] + + state.blkIndent = oldIndent + + return True diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/code.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/code.py new file mode 100644 index 0000000000000000000000000000000000000000..af8a41c8058b1a4887252469bdc6f20f085ad7d5 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/code.py @@ -0,0 +1,36 @@ +"""Code block (4 spaces padded).""" + +import logging + +from .state_block import StateBlock + +LOGGER = logging.getLogger(__name__) + + +def code(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool: + LOGGER.debug("entering code: %s, %s, %s, %s", state, startLine, endLine, silent) + + if not state.is_code_block(startLine): + return False + + last = nextLine = startLine + 1 + + while nextLine < endLine: + if state.isEmpty(nextLine): + nextLine += 1 + continue + + if state.is_code_block(nextLine): + nextLine += 1 + last = nextLine + continue + + break + + state.line = last + + token = state.push("code_block", "code", 0) + token.content = state.getLines(startLine, last, 4 + state.blkIndent, False) + "\n" + token.map = [startLine, state.line] + + return True diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/fence.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/fence.py new file mode 100644 index 0000000000000000000000000000000000000000..263f1b8de8dcdd0dd736eeafab2d9da34ec2c205 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/fence.py @@ -0,0 +1,101 @@ +# fences (``` lang, ~~~ lang) +import logging + +from .state_block import StateBlock + +LOGGER = logging.getLogger(__name__) + + +def fence(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool: + LOGGER.debug("entering fence: %s, %s, %s, %s", state, startLine, endLine, silent) + + haveEndMarker = False + pos = state.bMarks[startLine] + state.tShift[startLine] + maximum = state.eMarks[startLine] + + if state.is_code_block(startLine): + return False + + if pos + 3 > maximum: + return False + + marker = state.src[pos] + + if marker not in ("~", "`"): + return False + + # scan marker length + mem = pos + pos = state.skipCharsStr(pos, marker) + + length = pos - mem + + if length < 3: + return False + + markup = state.src[mem:pos] + params = state.src[pos:maximum] + + if marker == "`" and marker in params: + return False + + # Since start is found, we can report success here in validation mode + if silent: + return True + + # search end of block + nextLine = startLine + + while True: + nextLine += 1 + if nextLine >= endLine: + # unclosed block should be autoclosed by end of document. + # also block seems to be autoclosed by end of parent + break + + pos = mem = state.bMarks[nextLine] + state.tShift[nextLine] + maximum = state.eMarks[nextLine] + + if pos < maximum and state.sCount[nextLine] < state.blkIndent: + # non-empty line with negative indent should stop the list: + # - ``` + # test + break + + try: + if state.src[pos] != marker: + continue + except IndexError: + break + + if state.is_code_block(nextLine): + continue + + pos = state.skipCharsStr(pos, marker) + + # closing code fence must be at least as long as the opening one + if pos - mem < length: + continue + + # make sure tail has spaces only + pos = state.skipSpaces(pos) + + if pos < maximum: + continue + + haveEndMarker = True + # found! + break + + # If a fence has heading spaces, they should be removed from its inner block + length = state.sCount[startLine] + + state.line = nextLine + (1 if haveEndMarker else 0) + + token = state.push("fence", "code", 0) + token.info = params + token.content = state.getLines(startLine + 1, nextLine, length, True) + token.markup = markup + token.map = [startLine, state.line] + + return True diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/heading.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/heading.py new file mode 100644 index 0000000000000000000000000000000000000000..afcf9ed458124e52b9b365a6c17440872ffa0975 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/heading.py @@ -0,0 +1,69 @@ +"""Atex heading (#, ##, ...)""" + +from __future__ import annotations + +import logging + +from ..common.utils import isStrSpace +from .state_block import StateBlock + +LOGGER = logging.getLogger(__name__) + + +def heading(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool: + LOGGER.debug("entering heading: %s, %s, %s, %s", state, startLine, endLine, silent) + + pos = state.bMarks[startLine] + state.tShift[startLine] + maximum = state.eMarks[startLine] + + if state.is_code_block(startLine): + return False + + ch: str | None = state.src[pos] + + if ch != "#" or pos >= maximum: + return False + + # count heading level + level = 1 + pos += 1 + try: + ch = state.src[pos] + except IndexError: + ch = None + while ch == "#" and pos < maximum and level <= 6: + level += 1 + pos += 1 + try: + ch = state.src[pos] + except IndexError: + ch = None + + if level > 6 or (pos < maximum and not isStrSpace(ch)): + return False + + if silent: + return True + + # Let's cut tails like ' ### ' from the end of string + + maximum = state.skipSpacesBack(maximum, pos) + tmp = state.skipCharsStrBack(maximum, "#", pos) + if tmp > pos and isStrSpace(state.src[tmp - 1]): + maximum = tmp + + state.line = startLine + 1 + + token = state.push("heading_open", "h" + str(level), 1) + token.markup = "########"[:level] + token.map = [startLine, state.line] + + token = state.push("inline", "", 0) + token.content = state.src[pos:maximum].strip() + token.map = [startLine, state.line] + token.children = [] + + token = state.push("heading_close", "h" + str(level), -1) + token.markup = "########"[:level] + + return True diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/hr.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/hr.py new file mode 100644 index 0000000000000000000000000000000000000000..fca7d79d2780a5e656e689ac4843b8464b4ab5bd --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/hr.py @@ -0,0 +1,56 @@ +"""Horizontal rule + +At least 3 of these characters on a line * - _ +""" + +import logging + +from ..common.utils import isStrSpace +from .state_block import StateBlock + +LOGGER = logging.getLogger(__name__) + + +def hr(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool: + LOGGER.debug("entering hr: %s, %s, %s, %s", state, startLine, endLine, silent) + + pos = state.bMarks[startLine] + state.tShift[startLine] + maximum = state.eMarks[startLine] + + if state.is_code_block(startLine): + return False + + try: + marker = state.src[pos] + except IndexError: + return False + pos += 1 + + # Check hr marker + if marker not in ("*", "-", "_"): + return False + + # markers can be mixed with spaces, but there should be at least 3 of them + + cnt = 1 + while pos < maximum: + ch = state.src[pos] + pos += 1 + if ch != marker and not isStrSpace(ch): + return False + if ch == marker: + cnt += 1 + + if cnt < 3: + return False + + if silent: + return True + + state.line = startLine + 1 + + token = state.push("hr", "hr", 0) + token.map = [startLine, state.line] + token.markup = marker * (cnt + 1) + + return True diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/html_block.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/html_block.py new file mode 100644 index 0000000000000000000000000000000000000000..3d43f6ee1deb527a42f4d99da40bd052d9b02886 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/html_block.py @@ -0,0 +1,90 @@ +# HTML block +from __future__ import annotations + +import logging +import re + +from ..common.html_blocks import block_names +from ..common.html_re import HTML_OPEN_CLOSE_TAG_STR +from .state_block import StateBlock + +LOGGER = logging.getLogger(__name__) + +# An array of opening and corresponding closing sequences for html tags, +# last argument defines whether it can terminate a paragraph or not +HTML_SEQUENCES: list[tuple[re.Pattern[str], re.Pattern[str], bool]] = [ + ( + re.compile(r"^<(script|pre|style|textarea)(?=(\s|>|$))", re.IGNORECASE), + re.compile(r"<\/(script|pre|style|textarea)>", re.IGNORECASE), + True, + ), + (re.compile(r"^"), True), + (re.compile(r"^<\?"), re.compile(r"\?>"), True), + (re.compile(r"^"), True), + (re.compile(r"^"), True), + ( + re.compile("^|$))", re.IGNORECASE), + re.compile(r"^$"), + True, + ), + (re.compile(HTML_OPEN_CLOSE_TAG_STR + "\\s*$"), re.compile(r"^$"), False), +] + + +def html_block(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool: + LOGGER.debug( + "entering html_block: %s, %s, %s, %s", state, startLine, endLine, silent + ) + pos = state.bMarks[startLine] + state.tShift[startLine] + maximum = state.eMarks[startLine] + + if state.is_code_block(startLine): + return False + + if not state.md.options.get("html", None): + return False + + if state.src[pos] != "<": + return False + + lineText = state.src[pos:maximum] + + html_seq = None + for HTML_SEQUENCE in HTML_SEQUENCES: + if HTML_SEQUENCE[0].search(lineText): + html_seq = HTML_SEQUENCE + break + + if not html_seq: + return False + + if silent: + # true if this sequence can be a terminator, false otherwise + return html_seq[2] + + nextLine = startLine + 1 + + # If we are here - we detected HTML block. + # Let's roll down till block end. + if not html_seq[1].search(lineText): + while nextLine < endLine: + if state.sCount[nextLine] < state.blkIndent: + break + + pos = state.bMarks[nextLine] + state.tShift[nextLine] + maximum = state.eMarks[nextLine] + lineText = state.src[pos:maximum] + + if html_seq[1].search(lineText): + if len(lineText) != 0: + nextLine += 1 + break + nextLine += 1 + + state.line = nextLine + + token = state.push("html_block", "", 0) + token.map = [startLine, nextLine] + token.content = state.getLines(startLine, nextLine, state.blkIndent, True) + + return True diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/lheading.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/lheading.py new file mode 100644 index 0000000000000000000000000000000000000000..3522207abb680510decdd6c54d0be81401128ad7 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/lheading.py @@ -0,0 +1,86 @@ +# lheading (---, ==) +import logging + +from .state_block import StateBlock + +LOGGER = logging.getLogger(__name__) + + +def lheading(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool: + LOGGER.debug("entering lheading: %s, %s, %s, %s", state, startLine, endLine, silent) + + level = None + nextLine = startLine + 1 + ruler = state.md.block.ruler + terminatorRules = ruler.getRules("paragraph") + + if state.is_code_block(startLine): + return False + + oldParentType = state.parentType + state.parentType = "paragraph" # use paragraph to match terminatorRules + + # jump line-by-line until empty one or EOF + while nextLine < endLine and not state.isEmpty(nextLine): + # this would be a code block normally, but after paragraph + # it's considered a lazy continuation regardless of what's there + if state.sCount[nextLine] - state.blkIndent > 3: + nextLine += 1 + continue + + # Check for underline in setext header + if state.sCount[nextLine] >= state.blkIndent: + pos = state.bMarks[nextLine] + state.tShift[nextLine] + maximum = state.eMarks[nextLine] + + if pos < maximum: + marker = state.src[pos] + + if marker in ("-", "="): + pos = state.skipCharsStr(pos, marker) + pos = state.skipSpaces(pos) + + # /* = */ + if pos >= maximum: + level = 1 if marker == "=" else 2 + break + + # quirk for blockquotes, this line should already be checked by that rule + if state.sCount[nextLine] < 0: + nextLine += 1 + continue + + # Some tags can terminate paragraph without empty line. + terminate = False + for terminatorRule in terminatorRules: + if terminatorRule(state, nextLine, endLine, True): + terminate = True + break + if terminate: + break + + nextLine += 1 + + if not level: + # Didn't find valid underline + return False + + content = state.getLines(startLine, nextLine, state.blkIndent, False).strip() + + state.line = nextLine + 1 + + token = state.push("heading_open", "h" + str(level), 1) + token.markup = marker + token.map = [startLine, state.line] + + token = state.push("inline", "", 0) + token.content = content + token.map = [startLine, state.line - 1] + token.children = [] + + token = state.push("heading_close", "h" + str(level), -1) + token.markup = marker + + state.parentType = oldParentType + + return True diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/list.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/list.py new file mode 100644 index 0000000000000000000000000000000000000000..d8070d747035dd6b43f11c4bd88d05533b22bc5b --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/list.py @@ -0,0 +1,345 @@ +# Lists +import logging + +from ..common.utils import isStrSpace +from .state_block import StateBlock + +LOGGER = logging.getLogger(__name__) + + +# Search `[-+*][\n ]`, returns next pos after marker on success +# or -1 on fail. +def skipBulletListMarker(state: StateBlock, startLine: int) -> int: + pos = state.bMarks[startLine] + state.tShift[startLine] + maximum = state.eMarks[startLine] + + try: + marker = state.src[pos] + except IndexError: + return -1 + pos += 1 + + if marker not in ("*", "-", "+"): + return -1 + + if pos < maximum: + ch = state.src[pos] + + if not isStrSpace(ch): + # " -test " - is not a list item + return -1 + + return pos + + +# Search `\d+[.)][\n ]`, returns next pos after marker on success +# or -1 on fail. +def skipOrderedListMarker(state: StateBlock, startLine: int) -> int: + start = state.bMarks[startLine] + state.tShift[startLine] + pos = start + maximum = state.eMarks[startLine] + + # List marker should have at least 2 chars (digit + dot) + if pos + 1 >= maximum: + return -1 + + ch = state.src[pos] + pos += 1 + + ch_ord = ord(ch) + # /* 0 */ /* 9 */ + if ch_ord < 0x30 or ch_ord > 0x39: + return -1 + + while True: + # EOL -> fail + if pos >= maximum: + return -1 + + ch = state.src[pos] + pos += 1 + + # /* 0 */ /* 9 */ + ch_ord = ord(ch) + if ch_ord >= 0x30 and ch_ord <= 0x39: + # List marker should have no more than 9 digits + # (prevents integer overflow in browsers) + if pos - start >= 10: + return -1 + + continue + + # found valid marker + if ch in (")", "."): + break + + return -1 + + if pos < maximum: + ch = state.src[pos] + + if not isStrSpace(ch): + # " 1.test " - is not a list item + return -1 + + return pos + + +def markTightParagraphs(state: StateBlock, idx: int) -> None: + level = state.level + 2 + + i = idx + 2 + length = len(state.tokens) - 2 + while i < length: + if state.tokens[i].level == level and state.tokens[i].type == "paragraph_open": + state.tokens[i + 2].hidden = True + state.tokens[i].hidden = True + i += 2 + i += 1 + + +def list_block(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool: + LOGGER.debug("entering list: %s, %s, %s, %s", state, startLine, endLine, silent) + + isTerminatingParagraph = False + tight = True + + if state.is_code_block(startLine): + return False + + # Special case: + # - item 1 + # - item 2 + # - item 3 + # - item 4 + # - this one is a paragraph continuation + if ( + state.listIndent >= 0 + and state.sCount[startLine] - state.listIndent >= 4 + and state.sCount[startLine] < state.blkIndent + ): + return False + + # limit conditions when list can interrupt + # a paragraph (validation mode only) + # Next list item should still terminate previous list item + # + # This code can fail if plugins use blkIndent as well as lists, + # but I hope the spec gets fixed long before that happens. + # + if ( + silent + and state.parentType == "paragraph" + and state.sCount[startLine] >= state.blkIndent + ): + isTerminatingParagraph = True + + # Detect list type and position after marker + posAfterMarker = skipOrderedListMarker(state, startLine) + if posAfterMarker >= 0: + isOrdered = True + start = state.bMarks[startLine] + state.tShift[startLine] + markerValue = int(state.src[start : posAfterMarker - 1]) + + # If we're starting a new ordered list right after + # a paragraph, it should start with 1. + if isTerminatingParagraph and markerValue != 1: + return False + else: + posAfterMarker = skipBulletListMarker(state, startLine) + if posAfterMarker >= 0: + isOrdered = False + else: + return False + + # If we're starting a new unordered list right after + # a paragraph, first line should not be empty. + if ( + isTerminatingParagraph + and state.skipSpaces(posAfterMarker) >= state.eMarks[startLine] + ): + return False + + # We should terminate list on style change. Remember first one to compare. + markerChar = state.src[posAfterMarker - 1] + + # For validation mode we can terminate immediately + if silent: + return True + + # Start list + listTokIdx = len(state.tokens) + + if isOrdered: + token = state.push("ordered_list_open", "ol", 1) + if markerValue != 1: + token.attrs = {"start": markerValue} + + else: + token = state.push("bullet_list_open", "ul", 1) + + token.map = listLines = [startLine, 0] + token.markup = markerChar + + # + # Iterate list items + # + + nextLine = startLine + prevEmptyEnd = False + terminatorRules = state.md.block.ruler.getRules("list") + + oldParentType = state.parentType + state.parentType = "list" + + while nextLine < endLine: + pos = posAfterMarker + maximum = state.eMarks[nextLine] + + initial = offset = ( + state.sCount[nextLine] + + posAfterMarker + - (state.bMarks[startLine] + state.tShift[startLine]) + ) + + while pos < maximum: + ch = state.src[pos] + + if ch == "\t": + offset += 4 - (offset + state.bsCount[nextLine]) % 4 + elif ch == " ": + offset += 1 + else: + break + + pos += 1 + + contentStart = pos + + # trimming space in "- \n 3" case, indent is 1 here + indentAfterMarker = 1 if contentStart >= maximum else offset - initial + + # If we have more than 4 spaces, the indent is 1 + # (the rest is just indented code block) + if indentAfterMarker > 4: + indentAfterMarker = 1 + + # " - test" + # ^^^^^ - calculating total length of this thing + indent = initial + indentAfterMarker + + # Run subparser & write tokens + token = state.push("list_item_open", "li", 1) + token.markup = markerChar + token.map = itemLines = [startLine, 0] + if isOrdered: + token.info = state.src[start : posAfterMarker - 1] + + # change current state, then restore it after parser subcall + oldTight = state.tight + oldTShift = state.tShift[startLine] + oldSCount = state.sCount[startLine] + + # - example list + # ^ listIndent position will be here + # ^ blkIndent position will be here + # + oldListIndent = state.listIndent + state.listIndent = state.blkIndent + state.blkIndent = indent + + state.tight = True + state.tShift[startLine] = contentStart - state.bMarks[startLine] + state.sCount[startLine] = offset + + if contentStart >= maximum and state.isEmpty(startLine + 1): + # workaround for this case + # (list item is empty, list terminates before "foo"): + # ~~~~~~~~ + # - + # + # foo + # ~~~~~~~~ + state.line = min(state.line + 2, endLine) + else: + # NOTE in list.js this was: + # state.md.block.tokenize(state, startLine, endLine, True) + # but tokeniz does not take the final parameter + state.md.block.tokenize(state, startLine, endLine) + + # If any of list item is tight, mark list as tight + if (not state.tight) or prevEmptyEnd: + tight = False + + # Item become loose if finish with empty line, + # but we should filter last element, because it means list finish + prevEmptyEnd = (state.line - startLine) > 1 and state.isEmpty(state.line - 1) + + state.blkIndent = state.listIndent + state.listIndent = oldListIndent + state.tShift[startLine] = oldTShift + state.sCount[startLine] = oldSCount + state.tight = oldTight + + token = state.push("list_item_close", "li", -1) + token.markup = markerChar + + nextLine = startLine = state.line + itemLines[1] = nextLine + + if nextLine >= endLine: + break + + contentStart = state.bMarks[startLine] + + # + # Try to check if list is terminated or continued. + # + if state.sCount[nextLine] < state.blkIndent: + break + + if state.is_code_block(startLine): + break + + # fail if terminating block found + terminate = False + for terminatorRule in terminatorRules: + if terminatorRule(state, nextLine, endLine, True): + terminate = True + break + + if terminate: + break + + # fail if list has another type + if isOrdered: + posAfterMarker = skipOrderedListMarker(state, nextLine) + if posAfterMarker < 0: + break + start = state.bMarks[nextLine] + state.tShift[nextLine] + else: + posAfterMarker = skipBulletListMarker(state, nextLine) + if posAfterMarker < 0: + break + + if markerChar != state.src[posAfterMarker - 1]: + break + + # Finalize list + if isOrdered: + token = state.push("ordered_list_close", "ol", -1) + else: + token = state.push("bullet_list_close", "ul", -1) + + token.markup = markerChar + + listLines[1] = nextLine + state.line = nextLine + + state.parentType = oldParentType + + # mark paragraphs tight if needed + if tight: + markTightParagraphs(state, listTokIdx) + + return True diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/paragraph.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/paragraph.py new file mode 100644 index 0000000000000000000000000000000000000000..30ba877799beb764dc0a603caa21fe6e6b641375 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/paragraph.py @@ -0,0 +1,66 @@ +"""Paragraph.""" + +import logging + +from .state_block import StateBlock + +LOGGER = logging.getLogger(__name__) + + +def paragraph(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool: + LOGGER.debug( + "entering paragraph: %s, %s, %s, %s", state, startLine, endLine, silent + ) + + nextLine = startLine + 1 + ruler = state.md.block.ruler + terminatorRules = ruler.getRules("paragraph") + endLine = state.lineMax + + oldParentType = state.parentType + state.parentType = "paragraph" + + # jump line-by-line until empty one or EOF + while nextLine < endLine: + if state.isEmpty(nextLine): + break + # this would be a code block normally, but after paragraph + # it's considered a lazy continuation regardless of what's there + if state.sCount[nextLine] - state.blkIndent > 3: + nextLine += 1 + continue + + # quirk for blockquotes, this line should already be checked by that rule + if state.sCount[nextLine] < 0: + nextLine += 1 + continue + + # Some tags can terminate paragraph without empty line. + terminate = False + for terminatorRule in terminatorRules: + if terminatorRule(state, nextLine, endLine, True): + terminate = True + break + + if terminate: + break + + nextLine += 1 + + content = state.getLines(startLine, nextLine, state.blkIndent, False).strip() + + state.line = nextLine + + token = state.push("paragraph_open", "p", 1) + token.map = [startLine, state.line] + + token = state.push("inline", "", 0) + token.content = content + token.map = [startLine, state.line] + token.children = [] + + token = state.push("paragraph_close", "p", -1) + + state.parentType = oldParentType + + return True diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/reference.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..ad94d40941ee7cd43c7d3873ac64276a47c15d8b --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/reference.py @@ -0,0 +1,235 @@ +import logging + +from ..common.utils import charCodeAt, isSpace, normalizeReference +from .state_block import StateBlock + +LOGGER = logging.getLogger(__name__) + + +def reference(state: StateBlock, startLine: int, _endLine: int, silent: bool) -> bool: + LOGGER.debug( + "entering reference: %s, %s, %s, %s", state, startLine, _endLine, silent + ) + + pos = state.bMarks[startLine] + state.tShift[startLine] + maximum = state.eMarks[startLine] + nextLine = startLine + 1 + + if state.is_code_block(startLine): + return False + + if state.src[pos] != "[": + return False + + string = state.src[pos : maximum + 1] + + # string = state.getLines(startLine, nextLine, state.blkIndent, False).strip() + maximum = len(string) + + labelEnd = None + pos = 1 + while pos < maximum: + ch = charCodeAt(string, pos) + if ch == 0x5B: # /* [ */ + return False + elif ch == 0x5D: # /* ] */ + labelEnd = pos + break + elif ch == 0x0A: # /* \n */ + if (lineContent := getNextLine(state, nextLine)) is not None: + string += lineContent + maximum = len(string) + nextLine += 1 + elif ch == 0x5C: # /* \ */ + pos += 1 + if ( + pos < maximum + and charCodeAt(string, pos) == 0x0A + and (lineContent := getNextLine(state, nextLine)) is not None + ): + string += lineContent + maximum = len(string) + nextLine += 1 + pos += 1 + + if ( + labelEnd is None or labelEnd < 0 or charCodeAt(string, labelEnd + 1) != 0x3A + ): # /* : */ + return False + + # [label]: destination 'title' + # ^^^ skip optional whitespace here + pos = labelEnd + 2 + while pos < maximum: + ch = charCodeAt(string, pos) + if ch == 0x0A: + if (lineContent := getNextLine(state, nextLine)) is not None: + string += lineContent + maximum = len(string) + nextLine += 1 + elif isSpace(ch): + pass + else: + break + pos += 1 + + # [label]: destination 'title' + # ^^^^^^^^^^^ parse this + destRes = state.md.helpers.parseLinkDestination(string, pos, maximum) + if not destRes.ok: + return False + + href = state.md.normalizeLink(destRes.str) + if not state.md.validateLink(href): + return False + + pos = destRes.pos + + # save cursor state, we could require to rollback later + destEndPos = pos + destEndLineNo = nextLine + + # [label]: destination 'title' + # ^^^ skipping those spaces + start = pos + while pos < maximum: + ch = charCodeAt(string, pos) + if ch == 0x0A: + if (lineContent := getNextLine(state, nextLine)) is not None: + string += lineContent + maximum = len(string) + nextLine += 1 + elif isSpace(ch): + pass + else: + break + pos += 1 + + # [label]: destination 'title' + # ^^^^^^^ parse this + titleRes = state.md.helpers.parseLinkTitle(string, pos, maximum, None) + while titleRes.can_continue: + if (lineContent := getNextLine(state, nextLine)) is None: + break + string += lineContent + pos = maximum + maximum = len(string) + nextLine += 1 + titleRes = state.md.helpers.parseLinkTitle(string, pos, maximum, titleRes) + + if pos < maximum and start != pos and titleRes.ok: + title = titleRes.str + pos = titleRes.pos + else: + title = "" + pos = destEndPos + nextLine = destEndLineNo + + # skip trailing spaces until the rest of the line + while pos < maximum: + ch = charCodeAt(string, pos) + if not isSpace(ch): + break + pos += 1 + + if pos < maximum and charCodeAt(string, pos) != 0x0A and title: + # garbage at the end of the line after title, + # but it could still be a valid reference if we roll back + title = "" + pos = destEndPos + nextLine = destEndLineNo + while pos < maximum: + ch = charCodeAt(string, pos) + if not isSpace(ch): + break + pos += 1 + + if pos < maximum and charCodeAt(string, pos) != 0x0A: + # garbage at the end of the line + return False + + label = normalizeReference(string[1:labelEnd]) + if not label: + # CommonMark 0.20 disallows empty labels + return False + + # Reference can not terminate anything. This check is for safety only. + if silent: + return True + + if "references" not in state.env: + state.env["references"] = {} + + state.line = nextLine + + # note, this is not part of markdown-it JS, but is useful for renderers + if state.md.options.get("inline_definitions", False): + token = state.push("definition", "", 0) + token.meta = { + "id": label, + "title": title, + "url": href, + "label": string[1:labelEnd], + } + token.map = [startLine, state.line] + + if label not in state.env["references"]: + state.env["references"][label] = { + "title": title, + "href": href, + "map": [startLine, state.line], + } + else: + state.env.setdefault("duplicate_refs", []).append( + { + "title": title, + "href": href, + "label": label, + "map": [startLine, state.line], + } + ) + + return True + + +def getNextLine(state: StateBlock, nextLine: int) -> None | str: + endLine = state.lineMax + + if nextLine >= endLine or state.isEmpty(nextLine): + # empty line or end of input + return None + + isContinuation = False + + # this would be a code block normally, but after paragraph + # it's considered a lazy continuation regardless of what's there + if state.is_code_block(nextLine): + isContinuation = True + + # quirk for blockquotes, this line should already be checked by that rule + if state.sCount[nextLine] < 0: + isContinuation = True + + if not isContinuation: + terminatorRules = state.md.block.ruler.getRules("reference") + oldParentType = state.parentType + state.parentType = "reference" + + # Some tags can terminate paragraph without empty line. + terminate = False + for terminatorRule in terminatorRules: + if terminatorRule(state, nextLine, endLine, True): + terminate = True + break + + state.parentType = oldParentType + + if terminate: + # terminated by another block + return None + + pos = state.bMarks[nextLine] + state.tShift[nextLine] + maximum = state.eMarks[nextLine] + + # max + 1 explicitly includes the newline + return state.src[pos : maximum + 1] diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/state_block.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/state_block.py new file mode 100644 index 0000000000000000000000000000000000000000..445ad265a01e3f1dededf9f72848686a2b5ee901 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/state_block.py @@ -0,0 +1,261 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Literal + +from ..common.utils import isStrSpace +from ..ruler import StateBase +from ..token import Token +from ..utils import EnvType + +if TYPE_CHECKING: + from markdown_it.main import MarkdownIt + + +class StateBlock(StateBase): + def __init__( + self, src: str, md: MarkdownIt, env: EnvType, tokens: list[Token] + ) -> None: + self.src = src + + # link to parser instance + self.md = md + + self.env = env + + # + # Internal state variables + # + + self.tokens = tokens + + self.bMarks: list[int] = [] # line begin offsets for fast jumps + self.eMarks: list[int] = [] # line end offsets for fast jumps + # offsets of the first non-space characters (tabs not expanded) + self.tShift: list[int] = [] + self.sCount: list[int] = [] # indents for each line (tabs expanded) + + # An amount of virtual spaces (tabs expanded) between beginning + # of each line (bMarks) and real beginning of that line. + # + # It exists only as a hack because blockquotes override bMarks + # losing information in the process. + # + # It's used only when expanding tabs, you can think about it as + # an initial tab length, e.g. bsCount=21 applied to string `\t123` + # means first tab should be expanded to 4-21%4 === 3 spaces. + # + self.bsCount: list[int] = [] + + # block parser variables + self.blkIndent = 0 # required block content indent (for example, if we are + # inside a list, it would be positioned after list marker) + self.line = 0 # line index in src + self.lineMax = 0 # lines count + self.tight = False # loose/tight mode for lists + self.ddIndent = -1 # indent of the current dd block (-1 if there isn't any) + self.listIndent = -1 # indent of the current list block (-1 if there isn't any) + + # can be 'blockquote', 'list', 'root', 'paragraph' or 'reference' + # used in lists to determine if they interrupt a paragraph + self.parentType = "root" + + self.level = 0 + + # renderer + self.result = "" + + # Create caches + # Generate markers. + indent_found = False + + start = pos = indent = offset = 0 + length = len(self.src) + + for pos, character in enumerate(self.src): + if not indent_found: + if isStrSpace(character): + indent += 1 + + if character == "\t": + offset += 4 - offset % 4 + else: + offset += 1 + continue + else: + indent_found = True + + if character == "\n" or pos == length - 1: + if character != "\n": + pos += 1 + self.bMarks.append(start) + self.eMarks.append(pos) + self.tShift.append(indent) + self.sCount.append(offset) + self.bsCount.append(0) + + indent_found = False + indent = 0 + offset = 0 + start = pos + 1 + + # Push fake entry to simplify cache bounds checks + self.bMarks.append(length) + self.eMarks.append(length) + self.tShift.append(0) + self.sCount.append(0) + self.bsCount.append(0) + + self.lineMax = len(self.bMarks) - 1 # don't count last fake line + + # pre-check if code blocks are enabled, to speed up is_code_block method + self._code_enabled = "code" in self.md["block"].ruler.get_active_rules() + + def __repr__(self) -> str: + return ( + f"{self.__class__.__name__}" + f"(line={self.line},level={self.level},tokens={len(self.tokens)})" + ) + + def push(self, ttype: str, tag: str, nesting: Literal[-1, 0, 1]) -> Token: + """Push new token to "stream".""" + token = Token(ttype, tag, nesting) + token.block = True + if nesting < 0: + self.level -= 1 # closing tag + token.level = self.level + if nesting > 0: + self.level += 1 # opening tag + self.tokens.append(token) + return token + + def isEmpty(self, line: int) -> bool: + """.""" + return (self.bMarks[line] + self.tShift[line]) >= self.eMarks[line] + + def skipEmptyLines(self, from_pos: int) -> int: + """.""" + while from_pos < self.lineMax: + try: + if (self.bMarks[from_pos] + self.tShift[from_pos]) < self.eMarks[ + from_pos + ]: + break + except IndexError: + pass + from_pos += 1 + return from_pos + + def skipSpaces(self, pos: int) -> int: + """Skip spaces from given position.""" + while True: + try: + current = self.src[pos] + except IndexError: + break + if not isStrSpace(current): + break + pos += 1 + return pos + + def skipSpacesBack(self, pos: int, minimum: int) -> int: + """Skip spaces from given position in reverse.""" + if pos <= minimum: + return pos + while pos > minimum: + pos -= 1 + if not isStrSpace(self.src[pos]): + return pos + 1 + return pos + + def skipChars(self, pos: int, code: int) -> int: + """Skip character code from given position.""" + while True: + try: + current = self.srcCharCode[pos] + except IndexError: + break + if current != code: + break + pos += 1 + return pos + + def skipCharsStr(self, pos: int, ch: str) -> int: + """Skip character string from given position.""" + while True: + try: + current = self.src[pos] + except IndexError: + break + if current != ch: + break + pos += 1 + return pos + + def skipCharsBack(self, pos: int, code: int, minimum: int) -> int: + """Skip character code reverse from given position - 1.""" + if pos <= minimum: + return pos + while pos > minimum: + pos -= 1 + if code != self.srcCharCode[pos]: + return pos + 1 + return pos + + def skipCharsStrBack(self, pos: int, ch: str, minimum: int) -> int: + """Skip character string reverse from given position - 1.""" + if pos <= minimum: + return pos + while pos > minimum: + pos -= 1 + if ch != self.src[pos]: + return pos + 1 + return pos + + def getLines(self, begin: int, end: int, indent: int, keepLastLF: bool) -> str: + """Cut lines range from source.""" + line = begin + if begin >= end: + return "" + + queue = [""] * (end - begin) + + i = 1 + while line < end: + lineIndent = 0 + lineStart = first = self.bMarks[line] + last = ( + self.eMarks[line] + 1 + if line + 1 < end or keepLastLF + else self.eMarks[line] + ) + + while (first < last) and (lineIndent < indent): + ch = self.src[first] + if isStrSpace(ch): + if ch == "\t": + lineIndent += 4 - (lineIndent + self.bsCount[line]) % 4 + else: + lineIndent += 1 + elif first - lineStart < self.tShift[line]: + lineIndent += 1 + else: + break + first += 1 + + if lineIndent > indent: + # partially expanding tabs in code blocks, e.g '\t\tfoobar' + # with indent=2 becomes ' \tfoobar' + queue[i - 1] = (" " * (lineIndent - indent)) + self.src[first:last] + else: + queue[i - 1] = self.src[first:last] + + line += 1 + i += 1 + + return "".join(queue) + + def is_code_block(self, line: int) -> bool: + """Check if line is a code block, + i.e. the code block rule is enabled and text is indented by more than 3 spaces. + """ + return self._code_enabled and (self.sCount[line] - self.blkIndent) >= 4 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/table.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/table.py new file mode 100644 index 0000000000000000000000000000000000000000..c52553d8c21265df65e23be253686ef00b3297eb --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_block/table.py @@ -0,0 +1,250 @@ +# GFM table, https://github.github.com/gfm/#tables-extension- +from __future__ import annotations + +import re + +from ..common.utils import charStrAt, isStrSpace +from .state_block import StateBlock + +headerLineRe = re.compile(r"^:?-+:?$") +enclosingPipesRe = re.compile(r"^\||\|$") + +# Limit the amount of empty autocompleted cells in a table, +# see https://github.com/markdown-it/markdown-it/issues/1000, +# Both pulldown-cmark and commonmark-hs limit the number of cells this way to ~200k. +# We set it to 65k, which can expand user input by a factor of x370 +# (256x256 square is 1.8kB expanded into 650kB). +MAX_AUTOCOMPLETED_CELLS = 0x10000 + + +def getLine(state: StateBlock, line: int) -> str: + pos = state.bMarks[line] + state.tShift[line] + maximum = state.eMarks[line] + + # return state.src.substr(pos, max - pos) + return state.src[pos:maximum] + + +def escapedSplit(string: str) -> list[str]: + result: list[str] = [] + pos = 0 + max = len(string) + isEscaped = False + lastPos = 0 + current = "" + ch = charStrAt(string, pos) + + while pos < max: + if ch == "|": + if not isEscaped: + # pipe separating cells, '|' + result.append(current + string[lastPos:pos]) + current = "" + lastPos = pos + 1 + else: + # escaped pipe, '\|' + current += string[lastPos : pos - 1] + lastPos = pos + + isEscaped = ch == "\\" + pos += 1 + + ch = charStrAt(string, pos) + + result.append(current + string[lastPos:]) + + return result + + +def table(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool: + tbodyLines = None + + # should have at least two lines + if startLine + 2 > endLine: + return False + + nextLine = startLine + 1 + + if state.sCount[nextLine] < state.blkIndent: + return False + + if state.is_code_block(nextLine): + return False + + # first character of the second line should be '|', '-', ':', + # and no other characters are allowed but spaces; + # basically, this is the equivalent of /^[-:|][-:|\s]*$/ regexp + + pos = state.bMarks[nextLine] + state.tShift[nextLine] + if pos >= state.eMarks[nextLine]: + return False + first_ch = state.src[pos] + pos += 1 + if first_ch not in ("|", "-", ":"): + return False + + if pos >= state.eMarks[nextLine]: + return False + second_ch = state.src[pos] + pos += 1 + if second_ch not in ("|", "-", ":") and not isStrSpace(second_ch): + return False + + # if first character is '-', then second character must not be a space + # (due to parsing ambiguity with list) + if first_ch == "-" and isStrSpace(second_ch): + return False + + while pos < state.eMarks[nextLine]: + ch = state.src[pos] + + if ch not in ("|", "-", ":") and not isStrSpace(ch): + return False + + pos += 1 + + lineText = getLine(state, startLine + 1) + + columns = lineText.split("|") + aligns = [] + for i in range(len(columns)): + t = columns[i].strip() + if not t: + # allow empty columns before and after table, but not in between columns; + # e.g. allow ` |---| `, disallow ` ---||--- ` + if i == 0 or i == len(columns) - 1: + continue + else: + return False + + if not headerLineRe.search(t): + return False + if charStrAt(t, len(t) - 1) == ":": + aligns.append("center" if charStrAt(t, 0) == ":" else "right") + elif charStrAt(t, 0) == ":": + aligns.append("left") + else: + aligns.append("") + + lineText = getLine(state, startLine).strip() + if "|" not in lineText: + return False + if state.is_code_block(startLine): + return False + columns = escapedSplit(lineText) + if columns and columns[0] == "": + columns.pop(0) + if columns and columns[-1] == "": + columns.pop() + + # header row will define an amount of columns in the entire table, + # and align row should be exactly the same (the rest of the rows can differ) + columnCount = len(columns) + if columnCount == 0 or columnCount != len(aligns): + return False + + if silent: + return True + + oldParentType = state.parentType + state.parentType = "table" + + # use 'blockquote' lists for termination because it's + # the most similar to tables + terminatorRules = state.md.block.ruler.getRules("blockquote") + + token = state.push("table_open", "table", 1) + token.map = tableLines = [startLine, 0] + + token = state.push("thead_open", "thead", 1) + token.map = [startLine, startLine + 1] + + token = state.push("tr_open", "tr", 1) + token.map = [startLine, startLine + 1] + + for i in range(len(columns)): + token = state.push("th_open", "th", 1) + if aligns[i]: + token.attrs = {"style": "text-align:" + aligns[i]} + + token = state.push("inline", "", 0) + # note in markdown-it this map was removed in v12.0.0 however, we keep it, + # since it is helpful to propagate to children tokens + token.map = [startLine, startLine + 1] + token.content = columns[i].strip() + token.children = [] + + token = state.push("th_close", "th", -1) + + token = state.push("tr_close", "tr", -1) + token = state.push("thead_close", "thead", -1) + + autocompleted_cells = 0 + nextLine = startLine + 2 + while nextLine < endLine: + if state.sCount[nextLine] < state.blkIndent: + break + + terminate = False + for i in range(len(terminatorRules)): + if terminatorRules[i](state, nextLine, endLine, True): + terminate = True + break + + if terminate: + break + lineText = getLine(state, nextLine).strip() + if not lineText: + break + if state.is_code_block(nextLine): + break + columns = escapedSplit(lineText) + if columns and columns[0] == "": + columns.pop(0) + if columns and columns[-1] == "": + columns.pop() + + # note: autocomplete count can be negative if user specifies more columns than header, + # but that does not affect intended use (which is limiting expansion) + autocompleted_cells += columnCount - len(columns) + if autocompleted_cells > MAX_AUTOCOMPLETED_CELLS: + break + + if nextLine == startLine + 2: + token = state.push("tbody_open", "tbody", 1) + token.map = tbodyLines = [startLine + 2, 0] + + token = state.push("tr_open", "tr", 1) + token.map = [nextLine, nextLine + 1] + + for i in range(columnCount): + token = state.push("td_open", "td", 1) + if aligns[i]: + token.attrs = {"style": "text-align:" + aligns[i]} + + token = state.push("inline", "", 0) + # note in markdown-it this map was removed in v12.0.0 however, we keep it, + # since it is helpful to propagate to children tokens + token.map = [nextLine, nextLine + 1] + try: + token.content = columns[i].strip() if columns[i] else "" + except IndexError: + token.content = "" + token.children = [] + + token = state.push("td_close", "td", -1) + + token = state.push("tr_close", "tr", -1) + + nextLine += 1 + + if tbodyLines: + token = state.push("tbody_close", "tbody", -1) + tbodyLines[1] = nextLine + + token = state.push("table_close", "table", -1) + + tableLines[1] = nextLine + state.parentType = oldParentType + state.line = nextLine + return True diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e7d775363c6e1d454e73a7e3fff9af3115be4339 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__init__.py @@ -0,0 +1,19 @@ +__all__ = ( + "StateCore", + "block", + "inline", + "linkify", + "normalize", + "replace", + "smartquotes", + "text_join", +) + +from .block import block +from .inline import inline +from .linkify import linkify +from .normalize import normalize +from .replacements import replace +from .smartquotes import smartquotes +from .state_core import StateCore +from .text_join import text_join diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8241be25955626f0a401c44ff5fb6d911ae359e2 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/block.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65c296e87f60e1b38c279845834d83a45f6ca9c9 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/block.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/inline.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/inline.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..264fb6a5dd67dcccb74425454e8c6a96cc753ffb Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/inline.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/linkify.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/linkify.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbee6becb2b8899f867a4e3cd40d75a211839bd5 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/linkify.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/normalize.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/normalize.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..46c7950619373e54b71d818a5e691c6a56980d55 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/normalize.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/replacements.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/replacements.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..663357acaac6ac1d50bdd58400cdf2662e60b5cf Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/replacements.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/smartquotes.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/smartquotes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b1680280282583ed72300fc9a0614007cdba598 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/smartquotes.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/state_core.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/state_core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66ef9e9a2a9db70d494b079e6fd359c3fc5c4d6e Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/state_core.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/text_join.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/text_join.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57f83d9fcdc2240389e5fa44719621ede5049244 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/__pycache__/text_join.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/block.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/block.py new file mode 100644 index 0000000000000000000000000000000000000000..a6c3bb8d7ae18880fd638690fb5b09beb78b103c --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/block.py @@ -0,0 +1,13 @@ +from ..token import Token +from .state_core import StateCore + + +def block(state: StateCore) -> None: + if state.inlineMode: + token = Token("inline", "", 0) + token.content = state.src + token.map = [0, 1] + token.children = [] + state.tokens.append(token) + else: + state.md.block.parse(state.src, state.md, state.env, state.tokens) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/inline.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/inline.py new file mode 100644 index 0000000000000000000000000000000000000000..c3fd0b5e25dda5d8a5a644cc9e460d0f92ae2d1d --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/inline.py @@ -0,0 +1,10 @@ +from .state_core import StateCore + + +def inline(state: StateCore) -> None: + """Parse inlines""" + for token in state.tokens: + if token.type == "inline": + if token.children is None: + token.children = [] + state.md.inline.parse(token.content, state.md, state.env, token.children) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/linkify.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/linkify.py new file mode 100644 index 0000000000000000000000000000000000000000..efbc9d4c9b1cbada1c936401b3421d73fbff5b64 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/linkify.py @@ -0,0 +1,149 @@ +from __future__ import annotations + +import re +from typing import Protocol + +from ..common.utils import arrayReplaceAt, isLinkClose, isLinkOpen +from ..token import Token +from .state_core import StateCore + +HTTP_RE = re.compile(r"^http://") +MAILTO_RE = re.compile(r"^mailto:") +TEST_MAILTO_RE = re.compile(r"^mailto:", flags=re.IGNORECASE) + + +def linkify(state: StateCore) -> None: + """Rule for identifying plain-text links.""" + if not state.md.options.linkify: + return + + if not state.md.linkify: + raise ModuleNotFoundError("Linkify enabled but not installed.") + + for inline_token in state.tokens: + if inline_token.type != "inline" or not state.md.linkify.pretest( + inline_token.content + ): + continue + + tokens = inline_token.children + + htmlLinkLevel = 0 + + # We scan from the end, to keep position when new tags added. + # Use reversed logic in links start/end match + assert tokens is not None + i = len(tokens) + while i >= 1: + i -= 1 + assert isinstance(tokens, list) + currentToken = tokens[i] + + # Skip content of markdown links + if currentToken.type == "link_close": + i -= 1 + while ( + tokens[i].level != currentToken.level + and tokens[i].type != "link_open" + ): + i -= 1 + continue + + # Skip content of html tag links + if currentToken.type == "html_inline": + if isLinkOpen(currentToken.content) and htmlLinkLevel > 0: + htmlLinkLevel -= 1 + if isLinkClose(currentToken.content): + htmlLinkLevel += 1 + if htmlLinkLevel > 0: + continue + + if currentToken.type == "text" and state.md.linkify.test( + currentToken.content + ): + text = currentToken.content + links: list[_LinkType] = state.md.linkify.match(text) or [] + + # Now split string to nodes + nodes = [] + level = currentToken.level + lastPos = 0 + + # forbid escape sequence at the start of the string, + # this avoids http\://example.com/ from being linkified as + # http://example.com/ + if ( + links + and links[0].index == 0 + and i > 0 + and tokens[i - 1].type == "text_special" + ): + links = links[1:] + + for link in links: + url = link.url + fullUrl = state.md.normalizeLink(url) + if not state.md.validateLink(fullUrl): + continue + + urlText = link.text + + # Linkifier might send raw hostnames like "example.com", where url + # starts with domain name. So we prepend http:// in those cases, + # and remove it afterwards. + if not link.schema: + urlText = HTTP_RE.sub( + "", state.md.normalizeLinkText("http://" + urlText) + ) + elif link.schema == "mailto:" and TEST_MAILTO_RE.search(urlText): + urlText = MAILTO_RE.sub( + "", state.md.normalizeLinkText("mailto:" + urlText) + ) + else: + urlText = state.md.normalizeLinkText(urlText) + + pos = link.index + + if pos > lastPos: + token = Token("text", "", 0) + token.content = text[lastPos:pos] + token.level = level + nodes.append(token) + + token = Token("link_open", "a", 1) + token.attrs = {"href": fullUrl} + token.level = level + level += 1 + token.markup = "linkify" + token.info = "auto" + nodes.append(token) + + token = Token("text", "", 0) + token.content = urlText + token.level = level + nodes.append(token) + + token = Token("link_close", "a", -1) + level -= 1 + token.level = level + token.markup = "linkify" + token.info = "auto" + nodes.append(token) + + lastPos = link.last_index + + if lastPos < len(text): + token = Token("text", "", 0) + token.content = text[lastPos:] + token.level = level + nodes.append(token) + + inline_token.children = tokens = arrayReplaceAt(tokens, i, nodes) + + +class _LinkType(Protocol): + url: str + text: str + index: int + last_index: int + schema: str | None diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/normalize.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/normalize.py new file mode 100644 index 0000000000000000000000000000000000000000..32439243ef6ebfa424d202ed63635983d4c9ea82 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/normalize.py @@ -0,0 +1,19 @@ +"""Normalize input string.""" + +import re + +from .state_core import StateCore + +# https://spec.commonmark.org/0.29/#line-ending +NEWLINES_RE = re.compile(r"\r\n?|\n") +NULL_RE = re.compile(r"\0") + + +def normalize(state: StateCore) -> None: + # Normalize newlines + string = NEWLINES_RE.sub("\n", state.src) + + # Replace NULL characters + string = NULL_RE.sub("\ufffd", string) + + state.src = string diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/replacements.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/replacements.py new file mode 100644 index 0000000000000000000000000000000000000000..bcc9980046bf76723245b1ca2543af132efe5541 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/replacements.py @@ -0,0 +1,127 @@ +"""Simple typographic replacements + +* ``(c)``, ``(C)`` → © +* ``(tm)``, ``(TM)`` → ™ +* ``(r)``, ``(R)`` → ® +* ``+-`` → ± +* ``...`` → … +* ``?....`` → ?.. +* ``!....`` → !.. +* ``????????`` → ??? +* ``!!!!!`` → !!! +* ``,,,`` → , +* ``--`` → &ndash +* ``---`` → &mdash +""" + +from __future__ import annotations + +import logging +import re + +from ..token import Token +from .state_core import StateCore + +LOGGER = logging.getLogger(__name__) + +# TODO: +# - fractionals 1/2, 1/4, 3/4 -> ½, ¼, ¾ +# - multiplication 2 x 4 -> 2 × 4 + +RARE_RE = re.compile(r"\+-|\.\.|\?\?\?\?|!!!!|,,|--") + +# Workaround for phantomjs - need regex without /g flag, +# or root check will fail every second time +# SCOPED_ABBR_TEST_RE = r"\((c|tm|r)\)" + +SCOPED_ABBR_RE = re.compile(r"\((c|tm|r)\)", flags=re.IGNORECASE) + +PLUS_MINUS_RE = re.compile(r"\+-") + +ELLIPSIS_RE = re.compile(r"\.{2,}") + +ELLIPSIS_QUESTION_EXCLAMATION_RE = re.compile(r"([?!])…") + +QUESTION_EXCLAMATION_RE = re.compile(r"([?!]){4,}") + +COMMA_RE = re.compile(r",{2,}") + +EM_DASH_RE = re.compile(r"(^|[^-])---(?=[^-]|$)", flags=re.MULTILINE) + +EN_DASH_RE = re.compile(r"(^|\s)--(?=\s|$)", flags=re.MULTILINE) + +EN_DASH_INDENT_RE = re.compile(r"(^|[^-\s])--(?=[^-\s]|$)", flags=re.MULTILINE) + + +SCOPED_ABBR = {"c": "©", "r": "®", "tm": "™"} + + +def replaceFn(match: re.Match[str]) -> str: + return SCOPED_ABBR[match.group(1).lower()] + + +def replace_scoped(inlineTokens: list[Token]) -> None: + inside_autolink = 0 + + for token in inlineTokens: + if token.type == "text" and not inside_autolink: + token.content = SCOPED_ABBR_RE.sub(replaceFn, token.content) + + if token.type == "link_open" and token.info == "auto": + inside_autolink -= 1 + + if token.type == "link_close" and token.info == "auto": + inside_autolink += 1 + + +def replace_rare(inlineTokens: list[Token]) -> None: + inside_autolink = 0 + + for token in inlineTokens: + if ( + token.type == "text" + and (not inside_autolink) + and RARE_RE.search(token.content) + ): + # +- -> ± + token.content = PLUS_MINUS_RE.sub("±", token.content) + + # .., ..., ....... -> … + token.content = ELLIPSIS_RE.sub("…", token.content) + + # but ?..... & !..... -> ?.. & !.. + token.content = ELLIPSIS_QUESTION_EXCLAMATION_RE.sub("\\1..", token.content) + token.content = QUESTION_EXCLAMATION_RE.sub("\\1\\1\\1", token.content) + + # ,, ,,, ,,,, -> , + token.content = COMMA_RE.sub(",", token.content) + + # em-dash + token.content = EM_DASH_RE.sub("\\1\u2014", token.content) + + # en-dash + token.content = EN_DASH_RE.sub("\\1\u2013", token.content) + token.content = EN_DASH_INDENT_RE.sub("\\1\u2013", token.content) + + if token.type == "link_open" and token.info == "auto": + inside_autolink -= 1 + + if token.type == "link_close" and token.info == "auto": + inside_autolink += 1 + + +def replace(state: StateCore) -> None: + if not state.md.options.typographer: + return + + for token in state.tokens: + if token.type != "inline": + continue + if token.children is None: + continue + + if SCOPED_ABBR_RE.search(token.content): + replace_scoped(token.children) + + if RARE_RE.search(token.content): + replace_rare(token.children) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/smartquotes.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/smartquotes.py new file mode 100644 index 0000000000000000000000000000000000000000..f9b8b457b6c134f5736fabd3b14dc746e75ab86b --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/smartquotes.py @@ -0,0 +1,202 @@ +"""Convert straight quotation marks to typographic ones""" + +from __future__ import annotations + +import re +from typing import Any + +from ..common.utils import charCodeAt, isMdAsciiPunct, isPunctChar, isWhiteSpace +from ..token import Token +from .state_core import StateCore + +QUOTE_TEST_RE = re.compile(r"['\"]") +QUOTE_RE = re.compile(r"['\"]") +APOSTROPHE = "\u2019" # ’ + + +def replaceAt(string: str, index: int, ch: str) -> str: + # When the index is negative, the behavior is different from the js version. + # But basically, the index will not be negative. + assert index >= 0 + return string[:index] + ch + string[index + 1 :] + + +def process_inlines(tokens: list[Token], state: StateCore) -> None: + stack: list[dict[str, Any]] = [] + + for i, token in enumerate(tokens): + thisLevel = token.level + + j = 0 + for j in range(len(stack))[::-1]: + if stack[j]["level"] <= thisLevel: + break + else: + # When the loop is terminated without a "break". + # Subtract 1 to get the same index as the js version. + j -= 1 + + stack = stack[: j + 1] + + if token.type != "text": + continue + + text = token.content + pos = 0 + maximum = len(text) + + while pos < maximum: + goto_outer = False + lastIndex = pos + t = QUOTE_RE.search(text[lastIndex:]) + if not t: + break + + canOpen = canClose = True + pos = t.start(0) + lastIndex + 1 + isSingle = t.group(0) == "'" + + # Find previous character, + # default to space if it's the beginning of the line + lastChar: None | int = 0x20 + + if t.start(0) + lastIndex - 1 >= 0: + lastChar = charCodeAt(text, t.start(0) + lastIndex - 1) + else: + for j in range(i)[::-1]: + if tokens[j].type == "softbreak" or tokens[j].type == "hardbreak": + break + # should skip all tokens except 'text', 'html_inline' or 'code_inline' + if not tokens[j].content: + continue + + lastChar = charCodeAt(tokens[j].content, len(tokens[j].content) - 1) + break + + # Find next character, + # default to space if it's the end of the line + nextChar: None | int = 0x20 + + if pos < maximum: + nextChar = charCodeAt(text, pos) + else: + for j in range(i + 1, len(tokens)): + # nextChar defaults to 0x20 + if tokens[j].type == "softbreak" or tokens[j].type == "hardbreak": + break + # should skip all tokens except 'text', 'html_inline' or 'code_inline' + if not tokens[j].content: + continue + + nextChar = charCodeAt(tokens[j].content, 0) + break + + isLastPunctChar = lastChar is not None and ( + isMdAsciiPunct(lastChar) or isPunctChar(chr(lastChar)) + ) + isNextPunctChar = nextChar is not None and ( + isMdAsciiPunct(nextChar) or isPunctChar(chr(nextChar)) + ) + + isLastWhiteSpace = lastChar is not None and isWhiteSpace(lastChar) + isNextWhiteSpace = nextChar is not None and isWhiteSpace(nextChar) + + if isNextWhiteSpace: # noqa: SIM114 + canOpen = False + elif isNextPunctChar and not (isLastWhiteSpace or isLastPunctChar): + canOpen = False + + if isLastWhiteSpace: # noqa: SIM114 + canClose = False + elif isLastPunctChar and not (isNextWhiteSpace or isNextPunctChar): + canClose = False + + if nextChar == 0x22 and t.group(0) == '"': # 0x22: " # noqa: SIM102 + if ( + lastChar is not None and lastChar >= 0x30 and lastChar <= 0x39 + ): # 0x30: 0, 0x39: 9 + # special case: 1"" - count first quote as an inch + canClose = canOpen = False + + if canOpen and canClose: + # Replace quotes in the middle of punctuation sequence, but not + # in the middle of the words, i.e.: + # + # 1. foo " bar " baz - not replaced + # 2. foo-"-bar-"-baz - replaced + # 3. foo"bar"baz - not replaced + canOpen = isLastPunctChar + canClose = isNextPunctChar + + if not canOpen and not canClose: + # middle of word + if isSingle: + token.content = replaceAt( + token.content, t.start(0) + lastIndex, APOSTROPHE + ) + continue + + if canClose: + # this could be a closing quote, rewind the stack to get a match + for j in range(len(stack))[::-1]: + item = stack[j] + if stack[j]["level"] < thisLevel: + break + if item["single"] == isSingle and stack[j]["level"] == thisLevel: + item = stack[j] + + if isSingle: + openQuote = state.md.options.quotes[2] + closeQuote = state.md.options.quotes[3] + else: + openQuote = state.md.options.quotes[0] + closeQuote = state.md.options.quotes[1] + + # replace token.content *before* tokens[item.token].content, + # because, if they are pointing at the same token, replaceAt + # could mess up indices when quote length != 1 + token.content = replaceAt( + token.content, t.start(0) + lastIndex, closeQuote + ) + tokens[item["token"]].content = replaceAt( + tokens[item["token"]].content, item["pos"], openQuote + ) + + pos += len(closeQuote) - 1 + if item["token"] == i: + pos += len(openQuote) - 1 + + text = token.content + maximum = len(text) + + stack = stack[:j] + goto_outer = True + break + if goto_outer: + goto_outer = False + continue + + if canOpen: + stack.append( + { + "token": i, + "pos": t.start(0) + lastIndex, + "single": isSingle, + "level": thisLevel, + } + ) + elif canClose and isSingle: + token.content = replaceAt( + token.content, t.start(0) + lastIndex, APOSTROPHE + ) + + +def smartquotes(state: StateCore) -> None: + if not state.md.options.typographer: + return + + for token in state.tokens: + if token.type != "inline" or not QUOTE_RE.search(token.content): + continue + if token.children is not None: + process_inlines(token.children, state) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/state_core.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/state_core.py new file mode 100644 index 0000000000000000000000000000000000000000..a938041d992fdf7ae3f2843a2e0f9ef298c45790 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/state_core.py @@ -0,0 +1,25 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from ..ruler import StateBase +from ..token import Token +from ..utils import EnvType + +if TYPE_CHECKING: + from markdown_it import MarkdownIt + + +class StateCore(StateBase): + def __init__( + self, + src: str, + md: MarkdownIt, + env: EnvType, + tokens: list[Token] | None = None, + ) -> None: + self.src = src + self.md = md # link to parser instance + self.env = env + self.tokens: list[Token] = tokens or [] + self.inlineMode = False diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/text_join.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/text_join.py new file mode 100644 index 0000000000000000000000000000000000000000..5379f6d7a8e9ea3ee27a6462a4108a26549ae520 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_core/text_join.py @@ -0,0 +1,35 @@ +"""Join raw text tokens with the rest of the text + +This is set as a separate rule to provide an opportunity for plugins +to run text replacements after text join, but before escape join. + +For example, `\\:)` shouldn't be replaced with an emoji. +""" + +from __future__ import annotations + +from ..token import Token +from .state_core import StateCore + + +def text_join(state: StateCore) -> None: + """Join raw text for escape sequences (`text_special`) tokens with the rest of the text""" + + for inline_token in state.tokens[:]: + if inline_token.type != "inline": + continue + + # convert text_special to text and join all adjacent text nodes + new_tokens: list[Token] = [] + for child_token in inline_token.children or []: + if child_token.type == "text_special": + child_token.type = "text" + if ( + child_token.type == "text" + and new_tokens + and new_tokens[-1].type == "text" + ): + new_tokens[-1].content += child_token.content + else: + new_tokens.append(child_token) + inline_token.children = new_tokens diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d82ef8fbcca54eab4bbb40e8410104eef7a27f57 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__init__.py @@ -0,0 +1,31 @@ +__all__ = ( + "StateInline", + "autolink", + "backtick", + "emphasis", + "entity", + "escape", + "fragments_join", + "html_inline", + "image", + "link", + "link_pairs", + "linkify", + "newline", + "strikethrough", + "text", +) +from . import emphasis, strikethrough +from .autolink import autolink +from .backticks import backtick +from .balance_pairs import link_pairs +from .entity import entity +from .escape import escape +from .fragments_join import fragments_join +from .html_inline import html_inline +from .image import image +from .link import link +from .linkify import linkify +from .newline import newline +from .state_inline import StateInline +from .text import text diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c539e22ff1f41881e7c2319855729c3889a3cb5c Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/autolink.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/autolink.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f1dd94fc95cb75a94a74380fd00a0241cbd4873 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/autolink.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/backticks.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/backticks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a16cf30617b627895ec2207a2258875d4e6200ef Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/backticks.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/balance_pairs.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/balance_pairs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..710768d18481ab541b57d1b3cfd36d280d08e539 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/balance_pairs.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/emphasis.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/emphasis.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6027d62f61ead12183957e440dcd9d1ee669ceb4 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/emphasis.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/entity.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/entity.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff0414b192a08d51893ed418041641e075b08474 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/entity.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/escape.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/escape.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de1eab34a58f9b9236b5f0e799ead23094d626c6 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/escape.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/fragments_join.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/fragments_join.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52209eb6974f86ef8e53d9bfadca5118a54c28e8 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/fragments_join.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/html_inline.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/html_inline.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca203c6220431b00a42823fa948c6ef847e87561 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/html_inline.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/image.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/image.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97699e05d65618cc57214f8156a2791173973351 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/image.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/link.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/link.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f514ffe16dfbe7b5ea0a4a02ac8e9d74c9360a2f Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/link.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/linkify.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/linkify.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f33f48f1a8fbba6ab204f9bf43c5a060728eb12 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/linkify.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/newline.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/newline.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42c4834b8be38c1417624bc98ec980242245c964 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/newline.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/state_inline.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/state_inline.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4208d0fd2170bb5e63681fe4bacb09b094270a4 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/state_inline.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/strikethrough.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/strikethrough.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..215d39a19f07b28cdf61bcfac7103df954775e3f Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/strikethrough.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/text.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/text.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4d9f13148f4b2a4db3916ddac2316c1b29f00cf Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/__pycache__/text.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/autolink.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/autolink.py new file mode 100644 index 0000000000000000000000000000000000000000..6546e2502f93a1b38a49c3fd728963a156cf0243 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/autolink.py @@ -0,0 +1,77 @@ +# Process autolinks '' +import re + +from .state_inline import StateInline + +EMAIL_RE = re.compile( + r"^([a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$" +) +AUTOLINK_RE = re.compile(r"^([a-zA-Z][a-zA-Z0-9+.\-]{1,31}):([^<>\x00-\x20]*)$") + + +def autolink(state: StateInline, silent: bool) -> bool: + pos = state.pos + + if state.src[pos] != "<": + return False + + start = state.pos + maximum = state.posMax + + while True: + pos += 1 + if pos >= maximum: + return False + + ch = state.src[pos] + + if ch == "<": + return False + if ch == ">": + break + + url = state.src[start + 1 : pos] + + if AUTOLINK_RE.search(url) is not None: + fullUrl = state.md.normalizeLink(url) + if not state.md.validateLink(fullUrl): + return False + + if not silent: + token = state.push("link_open", "a", 1) + token.attrs = {"href": fullUrl} + token.markup = "autolink" + token.info = "auto" + + token = state.push("text", "", 0) + token.content = state.md.normalizeLinkText(url) + + token = state.push("link_close", "a", -1) + token.markup = "autolink" + token.info = "auto" + + state.pos += len(url) + 2 + return True + + if EMAIL_RE.search(url) is not None: + fullUrl = state.md.normalizeLink("mailto:" + url) + if not state.md.validateLink(fullUrl): + return False + + if not silent: + token = state.push("link_open", "a", 1) + token.attrs = {"href": fullUrl} + token.markup = "autolink" + token.info = "auto" + + token = state.push("text", "", 0) + token.content = state.md.normalizeLinkText(url) + + token = state.push("link_close", "a", -1) + token.markup = "autolink" + token.info = "auto" + + state.pos += len(url) + 2 + return True + + return False diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/backticks.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/backticks.py new file mode 100644 index 0000000000000000000000000000000000000000..fc60d6b15cdfa7012a05bcf1ccbb06f44d870dfd --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/backticks.py @@ -0,0 +1,72 @@ +# Parse backticks +import re + +from .state_inline import StateInline + +regex = re.compile("^ (.+) $") + + +def backtick(state: StateInline, silent: bool) -> bool: + pos = state.pos + + if state.src[pos] != "`": + return False + + start = pos + pos += 1 + maximum = state.posMax + + # scan marker length + while pos < maximum and (state.src[pos] == "`"): + pos += 1 + + marker = state.src[start:pos] + openerLength = len(marker) + + if state.backticksScanned and state.backticks.get(openerLength, 0) <= start: + if not silent: + state.pending += marker + state.pos += openerLength + return True + + matchStart = matchEnd = pos + + # Nothing found in the cache, scan until the end of the line (or until marker is found) + while True: + try: + matchStart = state.src.index("`", matchEnd) + except ValueError: + break + matchEnd = matchStart + 1 + + # scan marker length + while matchEnd < maximum and (state.src[matchEnd] == "`"): + matchEnd += 1 + + closerLength = matchEnd - matchStart + + if closerLength == openerLength: + # Found matching closer length. + if not silent: + token = state.push("code_inline", "code", 0) + token.markup = marker + token.content = state.src[pos:matchStart].replace("\n", " ") + if ( + token.content.startswith(" ") + and token.content.endswith(" ") + and len(token.content.strip()) > 0 + ): + token.content = token.content[1:-1] + state.pos = matchEnd + return True + + # Some different length found, put it in cache as upper limit of where closer can be found + state.backticks[closerLength] = matchStart + + # Scanned through the end, didn't find anything + state.backticksScanned = True + + if not silent: + state.pending += marker + state.pos += openerLength + return True diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/balance_pairs.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/balance_pairs.py new file mode 100644 index 0000000000000000000000000000000000000000..9c63b27f7186eb99c61938d27309fda7e900b88d --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/balance_pairs.py @@ -0,0 +1,138 @@ +"""Balance paired characters (*, _, etc) in inline tokens.""" + +from __future__ import annotations + +from .state_inline import Delimiter, StateInline + + +def processDelimiters(state: StateInline, delimiters: list[Delimiter]) -> None: + """For each opening emphasis-like marker find a matching closing one.""" + if not delimiters: + return + + openersBottom = {} + maximum = len(delimiters) + + # headerIdx is the first delimiter of the current (where closer is) delimiter run + headerIdx = 0 + lastTokenIdx = -2 # needs any value lower than -1 + jumps: list[int] = [] + closerIdx = 0 + while closerIdx < maximum: + closer = delimiters[closerIdx] + + jumps.append(0) + + # markers belong to same delimiter run if: + # - they have adjacent tokens + # - AND markers are the same + # + if ( + delimiters[headerIdx].marker != closer.marker + or lastTokenIdx != closer.token - 1 + ): + headerIdx = closerIdx + lastTokenIdx = closer.token + + # Length is only used for emphasis-specific "rule of 3", + # if it's not defined (in strikethrough or 3rd party plugins), + # we can default it to 0 to disable those checks. + # + closer.length = closer.length or 0 + + if not closer.close: + closerIdx += 1 + continue + + # Previously calculated lower bounds (previous fails) + # for each marker, each delimiter length modulo 3, + # and for whether this closer can be an opener; + # https://github.com/commonmark/cmark/commit/34250e12ccebdc6372b8b49c44fab57c72443460 + if closer.marker not in openersBottom: + openersBottom[closer.marker] = [-1, -1, -1, -1, -1, -1] + + minOpenerIdx = openersBottom[closer.marker][ + (3 if closer.open else 0) + (closer.length % 3) + ] + + openerIdx = headerIdx - jumps[headerIdx] - 1 + + newMinOpenerIdx = openerIdx + + while openerIdx > minOpenerIdx: + opener = delimiters[openerIdx] + + if opener.marker != closer.marker: + openerIdx -= jumps[openerIdx] + 1 + continue + + if opener.open and opener.end < 0: + isOddMatch = False + + # from spec: + # + # If one of the delimiters can both open and close emphasis, then the + # sum of the lengths of the delimiter runs containing the opening and + # closing delimiters must not be a multiple of 3 unless both lengths + # are multiples of 3. + # + if ( + (opener.close or closer.open) + and ((opener.length + closer.length) % 3 == 0) + and (opener.length % 3 != 0 or closer.length % 3 != 0) + ): + isOddMatch = True + + if not isOddMatch: + # If previous delimiter cannot be an opener, we can safely skip + # the entire sequence in future checks. This is required to make + # sure algorithm has linear complexity (see *_*_*_*_*_... case). + # + if openerIdx > 0 and not delimiters[openerIdx - 1].open: + lastJump = jumps[openerIdx - 1] + 1 + else: + lastJump = 0 + + jumps[closerIdx] = closerIdx - openerIdx + lastJump + jumps[openerIdx] = lastJump + + closer.open = False + opener.end = closerIdx + opener.close = False + newMinOpenerIdx = -1 + + # treat next token as start of run, + # it optimizes skips in **<...>**a**<...>** pathological case + lastTokenIdx = -2 + + break + + openerIdx -= jumps[openerIdx] + 1 + + if newMinOpenerIdx != -1: + # If match for this delimiter run failed, we want to set lower bound for + # future lookups. This is required to make sure algorithm has linear + # complexity. + # + # See details here: + # https:#github.com/commonmark/cmark/issues/178#issuecomment-270417442 + # + openersBottom[closer.marker][ + (3 if closer.open else 0) + ((closer.length or 0) % 3) + ] = newMinOpenerIdx + + closerIdx += 1 + + +def link_pairs(state: StateInline) -> None: + tokens_meta = state.tokens_meta + maximum = len(state.tokens_meta) + + processDelimiters(state, state.delimiters) + + curr = 0 + while curr < maximum: + curr_meta = tokens_meta[curr] + if curr_meta and "delimiters" in curr_meta: + processDelimiters(state, curr_meta["delimiters"]) + curr += 1 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/emphasis.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/emphasis.py new file mode 100644 index 0000000000000000000000000000000000000000..9a98f9e216c94db0217e986270aaaa72fcc99f7f --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/emphasis.py @@ -0,0 +1,102 @@ +# Process *this* and _that_ +# +from __future__ import annotations + +from .state_inline import Delimiter, StateInline + + +def tokenize(state: StateInline, silent: bool) -> bool: + """Insert each marker as a separate text token, and add it to delimiter list""" + start = state.pos + marker = state.src[start] + + if silent: + return False + + if marker not in ("_", "*"): + return False + + scanned = state.scanDelims(state.pos, marker == "*") + + for _ in range(scanned.length): + token = state.push("text", "", 0) + token.content = marker + state.delimiters.append( + Delimiter( + marker=ord(marker), + length=scanned.length, + token=len(state.tokens) - 1, + end=-1, + open=scanned.can_open, + close=scanned.can_close, + ) + ) + + state.pos += scanned.length + + return True + + +def _postProcess(state: StateInline, delimiters: list[Delimiter]) -> None: + i = len(delimiters) - 1 + while i >= 0: + startDelim = delimiters[i] + + # /* _ */ /* * */ + if startDelim.marker != 0x5F and startDelim.marker != 0x2A: + i -= 1 + continue + + # Process only opening markers + if startDelim.end == -1: + i -= 1 + continue + + endDelim = delimiters[startDelim.end] + + # If the previous delimiter has the same marker and is adjacent to this one, + # merge those into one strong delimiter. + # + # `whatever` -> `whatever` + # + isStrong = ( + i > 0 + and delimiters[i - 1].end == startDelim.end + 1 + # check that first two markers match and adjacent + and delimiters[i - 1].marker == startDelim.marker + and delimiters[i - 1].token == startDelim.token - 1 + # check that last two markers are adjacent (we can safely assume they match) + and delimiters[startDelim.end + 1].token == endDelim.token + 1 + ) + + ch = chr(startDelim.marker) + + token = state.tokens[startDelim.token] + token.type = "strong_open" if isStrong else "em_open" + token.tag = "strong" if isStrong else "em" + token.nesting = 1 + token.markup = ch + ch if isStrong else ch + token.content = "" + + token = state.tokens[endDelim.token] + token.type = "strong_close" if isStrong else "em_close" + token.tag = "strong" if isStrong else "em" + token.nesting = -1 + token.markup = ch + ch if isStrong else ch + token.content = "" + + if isStrong: + state.tokens[delimiters[i - 1].token].content = "" + state.tokens[delimiters[startDelim.end + 1].token].content = "" + i -= 1 + + i -= 1 + + +def postProcess(state: StateInline) -> None: + """Walk through delimiter list and replace text tokens with tags.""" + _postProcess(state, state.delimiters) + + for token in state.tokens_meta: + if token and "delimiters" in token: + _postProcess(state, token["delimiters"]) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/entity.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/entity.py new file mode 100644 index 0000000000000000000000000000000000000000..ec9d39650e5bc533e694d3d6699677068d22c69f --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/entity.py @@ -0,0 +1,53 @@ +# Process html entity - {, ¯, ", ... +import re + +from ..common.entities import entities +from ..common.utils import fromCodePoint, isValidEntityCode +from .state_inline import StateInline + +DIGITAL_RE = re.compile(r"^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));", re.IGNORECASE) +NAMED_RE = re.compile(r"^&([a-z][a-z0-9]{1,31});", re.IGNORECASE) + + +def entity(state: StateInline, silent: bool) -> bool: + pos = state.pos + maximum = state.posMax + + if state.src[pos] != "&": + return False + + if pos + 1 >= maximum: + return False + + if state.src[pos + 1] == "#": + if match := DIGITAL_RE.search(state.src[pos:]): + if not silent: + match1 = match.group(1) + code = ( + int(match1[1:], 16) if match1[0].lower() == "x" else int(match1, 10) + ) + + token = state.push("text_special", "", 0) + token.content = ( + fromCodePoint(code) + if isValidEntityCode(code) + else fromCodePoint(0xFFFD) + ) + token.markup = match.group(0) + token.info = "entity" + + state.pos += len(match.group(0)) + return True + + else: + if (match := NAMED_RE.search(state.src[pos:])) and match.group(1) in entities: + if not silent: + token = state.push("text_special", "", 0) + token.content = entities[match.group(1)] + token.markup = match.group(0) + token.info = "entity" + + state.pos += len(match.group(0)) + return True + + return False diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/escape.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/escape.py new file mode 100644 index 0000000000000000000000000000000000000000..0fca6c84e035b83b21d5224be92fd4973f25b80b --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/escape.py @@ -0,0 +1,93 @@ +""" +Process escaped chars and hardbreaks +""" + +from ..common.utils import isStrSpace +from .state_inline import StateInline + + +def escape(state: StateInline, silent: bool) -> bool: + """Process escaped chars and hardbreaks.""" + pos = state.pos + maximum = state.posMax + + if state.src[pos] != "\\": + return False + + pos += 1 + + # '\' at the end of the inline block + if pos >= maximum: + return False + + ch1 = state.src[pos] + ch1_ord = ord(ch1) + if ch1 == "\n": + if not silent: + state.push("hardbreak", "br", 0) + pos += 1 + # skip leading whitespaces from next line + while pos < maximum: + ch = state.src[pos] + if not isStrSpace(ch): + break + pos += 1 + + state.pos = pos + return True + + escapedStr = state.src[pos] + + if ch1_ord >= 0xD800 and ch1_ord <= 0xDBFF and pos + 1 < maximum: + ch2 = state.src[pos + 1] + ch2_ord = ord(ch2) + if ch2_ord >= 0xDC00 and ch2_ord <= 0xDFFF: + escapedStr += ch2 + pos += 1 + + origStr = "\\" + escapedStr + + if not silent: + token = state.push("text_special", "", 0) + token.content = escapedStr if ch1 in _ESCAPED else origStr + token.markup = origStr + token.info = "escape" + + state.pos = pos + 1 + return True + + +_ESCAPED = { + "!", + '"', + "#", + "$", + "%", + "&", + "'", + "(", + ")", + "*", + "+", + ",", + "-", + ".", + "/", + ":", + ";", + "<", + "=", + ">", + "?", + "@", + "[", + "\\", + "]", + "^", + "_", + "`", + "{", + "|", + "}", + "~", +} diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/fragments_join.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/fragments_join.py new file mode 100644 index 0000000000000000000000000000000000000000..f795c1364b8ac098b7a17f34cd31d7070280cf36 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/fragments_join.py @@ -0,0 +1,43 @@ +from .state_inline import StateInline + + +def fragments_join(state: StateInline) -> None: + """ + Clean up tokens after emphasis and strikethrough postprocessing: + merge adjacent text nodes into one and re-calculate all token levels + + This is necessary because initially emphasis delimiter markers (``*, _, ~``) + are treated as their own separate text tokens. Then emphasis rule either + leaves them as text (needed to merge with adjacent text) or turns them + into opening/closing tags (which messes up levels inside). + """ + level = 0 + maximum = len(state.tokens) + + curr = last = 0 + while curr < maximum: + # re-calculate levels after emphasis/strikethrough turns some text nodes + # into opening/closing tags + if state.tokens[curr].nesting < 0: + level -= 1 # closing tag + state.tokens[curr].level = level + if state.tokens[curr].nesting > 0: + level += 1 # opening tag + + if ( + state.tokens[curr].type == "text" + and curr + 1 < maximum + and state.tokens[curr + 1].type == "text" + ): + # collapse two adjacent text nodes + state.tokens[curr + 1].content = ( + state.tokens[curr].content + state.tokens[curr + 1].content + ) + else: + if curr != last: + state.tokens[last] = state.tokens[curr] + last += 1 + curr += 1 + + if curr != last: + del state.tokens[last:] diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/html_inline.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/html_inline.py new file mode 100644 index 0000000000000000000000000000000000000000..9065e1d034da76270f7d3f1ba528132c8d57d341 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/html_inline.py @@ -0,0 +1,43 @@ +# Process html tags +from ..common.html_re import HTML_TAG_RE +from ..common.utils import isLinkClose, isLinkOpen +from .state_inline import StateInline + + +def isLetter(ch: int) -> bool: + lc = ch | 0x20 # to lower case + # /* a */ and /* z */ + return (lc >= 0x61) and (lc <= 0x7A) + + +def html_inline(state: StateInline, silent: bool) -> bool: + pos = state.pos + + if not state.md.options.get("html", None): + return False + + # Check start + maximum = state.posMax + if state.src[pos] != "<" or pos + 2 >= maximum: + return False + + # Quick fail on second char + ch = state.src[pos + 1] + if ch not in ("!", "?", "/") and not isLetter(ord(ch)): # /* / */ + return False + + match = HTML_TAG_RE.search(state.src[pos:]) + if not match: + return False + + if not silent: + token = state.push("html_inline", "", 0) + token.content = state.src[pos : pos + len(match.group(0))] + + if isLinkOpen(token.content): + state.linkLevel += 1 + if isLinkClose(token.content): + state.linkLevel -= 1 + + state.pos += len(match.group(0)) + return True diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/image.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/image.py new file mode 100644 index 0000000000000000000000000000000000000000..005105b1c7ed1a93772c62af8bd5ef54d97dfebe --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/image.py @@ -0,0 +1,148 @@ +# Process ![image]( "title") +from __future__ import annotations + +from ..common.utils import isStrSpace, normalizeReference +from ..token import Token +from .state_inline import StateInline + + +def image(state: StateInline, silent: bool) -> bool: + label = None + href = "" + oldPos = state.pos + max = state.posMax + + if state.src[state.pos] != "!": + return False + + if state.pos + 1 < state.posMax and state.src[state.pos + 1] != "[": + return False + + labelStart = state.pos + 2 + labelEnd = state.md.helpers.parseLinkLabel(state, state.pos + 1, False) + + # parser failed to find ']', so it's not a valid link + if labelEnd < 0: + return False + + pos = labelEnd + 1 + + if pos < max and state.src[pos] == "(": + # + # Inline link + # + + # [link]( "title" ) + # ^^ skipping these spaces + pos += 1 + while pos < max: + ch = state.src[pos] + if not isStrSpace(ch) and ch != "\n": + break + pos += 1 + + if pos >= max: + return False + + # [link]( "title" ) + # ^^^^^^ parsing link destination + start = pos + res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax) + if res.ok: + href = state.md.normalizeLink(res.str) + if state.md.validateLink(href): + pos = res.pos + else: + href = "" + + # [link]( "title" ) + # ^^ skipping these spaces + start = pos + while pos < max: + ch = state.src[pos] + if not isStrSpace(ch) and ch != "\n": + break + pos += 1 + + # [link]( "title" ) + # ^^^^^^^ parsing link title + res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax, None) + if pos < max and start != pos and res.ok: + title = res.str + pos = res.pos + + # [link]( "title" ) + # ^^ skipping these spaces + while pos < max: + ch = state.src[pos] + if not isStrSpace(ch) and ch != "\n": + break + pos += 1 + else: + title = "" + + if pos >= max or state.src[pos] != ")": + state.pos = oldPos + return False + + pos += 1 + + else: + # + # Link reference + # + if "references" not in state.env: + return False + + # /* [ */ + if pos < max and state.src[pos] == "[": + start = pos + 1 + pos = state.md.helpers.parseLinkLabel(state, pos) + if pos >= 0: + label = state.src[start:pos] + pos += 1 + else: + pos = labelEnd + 1 + else: + pos = labelEnd + 1 + + # covers label == '' and label == undefined + # (collapsed reference link and shortcut reference link respectively) + if not label: + label = state.src[labelStart:labelEnd] + + label = normalizeReference(label) + + ref = state.env["references"].get(label, None) + if not ref: + state.pos = oldPos + return False + + href = ref["href"] + title = ref["title"] + + # + # We found the end of the link, and know for a fact it's a valid link + # so all that's left to do is to call tokenizer. + # + if not silent: + content = state.src[labelStart:labelEnd] + + tokens: list[Token] = [] + state.md.inline.parse(content, state.md, state.env, tokens) + + token = state.push("image", "img", 0) + token.attrs = {"src": href, "alt": ""} + token.children = tokens or None + token.content = content + + if title: + token.attrSet("title", title) + + # note, this is not part of markdown-it JS, but is useful for renderers + if label and state.md.options.get("store_labels", False): + token.meta["label"] = label + + state.pos = pos + state.posMax = max + return True diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/link.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/link.py new file mode 100644 index 0000000000000000000000000000000000000000..2e92c7d83629f00283b5ed885637c8c4a851ffc7 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/link.py @@ -0,0 +1,149 @@ +# Process [link]( "stuff") + +from ..common.utils import isStrSpace, normalizeReference +from .state_inline import StateInline + + +def link(state: StateInline, silent: bool) -> bool: + href = "" + title = "" + label = None + oldPos = state.pos + maximum = state.posMax + start = state.pos + parseReference = True + + if state.src[state.pos] != "[": + return False + + labelStart = state.pos + 1 + labelEnd = state.md.helpers.parseLinkLabel(state, state.pos, True) + + # parser failed to find ']', so it's not a valid link + if labelEnd < 0: + return False + + pos = labelEnd + 1 + + if pos < maximum and state.src[pos] == "(": + # + # Inline link + # + + # might have found a valid shortcut link, disable reference parsing + parseReference = False + + # [link]( "title" ) + # ^^ skipping these spaces + pos += 1 + while pos < maximum: + ch = state.src[pos] + if not isStrSpace(ch) and ch != "\n": + break + pos += 1 + + if pos >= maximum: + return False + + # [link]( "title" ) + # ^^^^^^ parsing link destination + start = pos + res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax) + if res.ok: + href = state.md.normalizeLink(res.str) + if state.md.validateLink(href): + pos = res.pos + else: + href = "" + + # [link]( "title" ) + # ^^ skipping these spaces + start = pos + while pos < maximum: + ch = state.src[pos] + if not isStrSpace(ch) and ch != "\n": + break + pos += 1 + + # [link]( "title" ) + # ^^^^^^^ parsing link title + res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax) + if pos < maximum and start != pos and res.ok: + title = res.str + pos = res.pos + + # [link]( "title" ) + # ^^ skipping these spaces + while pos < maximum: + ch = state.src[pos] + if not isStrSpace(ch) and ch != "\n": + break + pos += 1 + + if pos >= maximum or state.src[pos] != ")": + # parsing a valid shortcut link failed, fallback to reference + parseReference = True + + pos += 1 + + if parseReference: + # + # Link reference + # + if "references" not in state.env: + return False + + if pos < maximum and state.src[pos] == "[": + start = pos + 1 + pos = state.md.helpers.parseLinkLabel(state, pos) + if pos >= 0: + label = state.src[start:pos] + pos += 1 + else: + pos = labelEnd + 1 + + else: + pos = labelEnd + 1 + + # covers label == '' and label == undefined + # (collapsed reference link and shortcut reference link respectively) + if not label: + label = state.src[labelStart:labelEnd] + + label = normalizeReference(label) + + ref = state.env["references"].get(label, None) + if not ref: + state.pos = oldPos + return False + + href = ref["href"] + title = ref["title"] + + # + # We found the end of the link, and know for a fact it's a valid link + # so all that's left to do is to call tokenizer. + # + if not silent: + state.pos = labelStart + state.posMax = labelEnd + + token = state.push("link_open", "a", 1) + token.attrs = {"href": href} + + if title: + token.attrSet("title", title) + + # note, this is not part of markdown-it JS, but is useful for renderers + if label and state.md.options.get("store_labels", False): + token.meta["label"] = label + + state.linkLevel += 1 + state.md.inline.tokenize(state) + state.linkLevel -= 1 + + token = state.push("link_close", "a", -1) + + state.pos = pos + state.posMax = maximum + return True diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/linkify.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/linkify.py new file mode 100644 index 0000000000000000000000000000000000000000..3669396e3e7d51c125678f45a862139fe3b3fd9d --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/linkify.py @@ -0,0 +1,62 @@ +"""Process links like https://example.org/""" + +import re + +from .state_inline import StateInline + +# RFC3986: scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) +SCHEME_RE = re.compile(r"(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$", re.IGNORECASE) + + +def linkify(state: StateInline, silent: bool) -> bool: + """Rule for identifying plain-text links.""" + if not state.md.options.linkify: + return False + if state.linkLevel > 0: + return False + if not state.md.linkify: + raise ModuleNotFoundError("Linkify enabled but not installed.") + + pos = state.pos + maximum = state.posMax + + if ( + (pos + 3) > maximum + or state.src[pos] != ":" + or state.src[pos + 1] != "/" + or state.src[pos + 2] != "/" + ): + return False + + if not (match := SCHEME_RE.search(state.pending)): + return False + + proto = match.group(1) + if not (link := state.md.linkify.match_at_start(state.src[pos - len(proto) :])): + return False + url: str = link.url + + # disallow '*' at the end of the link (conflicts with emphasis) + url = url.rstrip("*") + + full_url = state.md.normalizeLink(url) + if not state.md.validateLink(full_url): + return False + + if not silent: + state.pending = state.pending[: -len(proto)] + + token = state.push("link_open", "a", 1) + token.attrs = {"href": full_url} + token.markup = "linkify" + token.info = "auto" + + token = state.push("text", "", 0) + token.content = state.md.normalizeLinkText(url) + + token = state.push("link_close", "a", -1) + token.markup = "linkify" + token.info = "auto" + + state.pos += len(url) - len(proto) + return True diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/newline.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/newline.py new file mode 100644 index 0000000000000000000000000000000000000000..d05ee6dac712a2211ab24f90dbea64a99e4d80b0 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/newline.py @@ -0,0 +1,44 @@ +"""Proceess '\n'.""" + +from ..common.utils import charStrAt, isStrSpace +from .state_inline import StateInline + + +def newline(state: StateInline, silent: bool) -> bool: + pos = state.pos + + if state.src[pos] != "\n": + return False + + pmax = len(state.pending) - 1 + maximum = state.posMax + + # ' \n' -> hardbreak + # Lookup in pending chars is bad practice! Don't copy to other rules! + # Pending string is stored in concat mode, indexed lookups will cause + # conversion to flat mode. + if not silent: + if pmax >= 0 and charStrAt(state.pending, pmax) == " ": + if pmax >= 1 and charStrAt(state.pending, pmax - 1) == " ": + # Find whitespaces tail of pending chars. + ws = pmax - 1 + while ws >= 1 and charStrAt(state.pending, ws - 1) == " ": + ws -= 1 + state.pending = state.pending[:ws] + + state.push("hardbreak", "br", 0) + else: + state.pending = state.pending[:-1] + state.push("softbreak", "br", 0) + + else: + state.push("softbreak", "br", 0) + + pos += 1 + + # skip heading spaces for next line + while pos < maximum and isStrSpace(state.src[pos]): + pos += 1 + + state.pos = pos + return True diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/state_inline.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/state_inline.py new file mode 100644 index 0000000000000000000000000000000000000000..50dc41294d6b3df03f73bfb40d740ea4ba36c8ee --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/state_inline.py @@ -0,0 +1,165 @@ +from __future__ import annotations + +from collections import namedtuple +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Literal + +from ..common.utils import isMdAsciiPunct, isPunctChar, isWhiteSpace +from ..ruler import StateBase +from ..token import Token +from ..utils import EnvType + +if TYPE_CHECKING: + from markdown_it import MarkdownIt + + +@dataclass(slots=True) +class Delimiter: + # Char code of the starting marker (number). + marker: int + + # Total length of these series of delimiters. + length: int + + # A position of the token this delimiter corresponds to. + token: int + + # If this delimiter is matched as a valid opener, `end` will be + # equal to its position, otherwise it's `-1`. + end: int + + # Boolean flags that determine if this delimiter could open or close + # an emphasis. + open: bool + close: bool + + level: bool | None = None + + +Scanned = namedtuple("Scanned", ["can_open", "can_close", "length"]) + + +class StateInline(StateBase): + def __init__( + self, src: str, md: MarkdownIt, env: EnvType, outTokens: list[Token] + ) -> None: + self.src = src + self.env = env + self.md = md + self.tokens = outTokens + self.tokens_meta: list[dict[str, Any] | None] = [None] * len(outTokens) + + self.pos = 0 + self.posMax = len(self.src) + self.level = 0 + self.pending = "" + self.pendingLevel = 0 + + # Stores { start: end } pairs. Useful for backtrack + # optimization of pairs parse (emphasis, strikes). + self.cache: dict[int, int] = {} + + # List of emphasis-like delimiters for current tag + self.delimiters: list[Delimiter] = [] + + # Stack of delimiter lists for upper level tags + self._prev_delimiters: list[list[Delimiter]] = [] + + # backticklength => last seen position + self.backticks: dict[int, int] = {} + self.backticksScanned = False + + # Counter used to disable inline linkify-it execution + # inside and markdown links + self.linkLevel = 0 + + def __repr__(self) -> str: + return ( + f"{self.__class__.__name__}" + f"(pos=[{self.pos} of {self.posMax}], token={len(self.tokens)})" + ) + + def pushPending(self) -> Token: + token = Token("text", "", 0) + token.content = self.pending + token.level = self.pendingLevel + self.tokens.append(token) + self.pending = "" + return token + + def push(self, ttype: str, tag: str, nesting: Literal[-1, 0, 1]) -> Token: + """Push new token to "stream". + If pending text exists - flush it as text token + """ + if self.pending: + self.pushPending() + + token = Token(ttype, tag, nesting) + token_meta = None + + if nesting < 0: + # closing tag + self.level -= 1 + self.delimiters = self._prev_delimiters.pop() + + token.level = self.level + + if nesting > 0: + # opening tag + self.level += 1 + self._prev_delimiters.append(self.delimiters) + self.delimiters = [] + token_meta = {"delimiters": self.delimiters} + + self.pendingLevel = self.level + self.tokens.append(token) + self.tokens_meta.append(token_meta) + return token + + def scanDelims(self, start: int, canSplitWord: bool) -> Scanned: + """ + Scan a sequence of emphasis-like markers, and determine whether + it can start an emphasis sequence or end an emphasis sequence. + + - start - position to scan from (it should point at a valid marker); + - canSplitWord - determine if these markers can be found inside a word + + """ + pos = start + maximum = self.posMax + marker = self.src[start] + + # treat beginning of the line as a whitespace + lastChar = self.src[start - 1] if start > 0 else " " + + while pos < maximum and self.src[pos] == marker: + pos += 1 + + count = pos - start + + # treat end of the line as a whitespace + nextChar = self.src[pos] if pos < maximum else " " + + isLastPunctChar = isMdAsciiPunct(ord(lastChar)) or isPunctChar(lastChar) + isNextPunctChar = isMdAsciiPunct(ord(nextChar)) or isPunctChar(nextChar) + + isLastWhiteSpace = isWhiteSpace(ord(lastChar)) + isNextWhiteSpace = isWhiteSpace(ord(nextChar)) + + left_flanking = not ( + isNextWhiteSpace + or (isNextPunctChar and not (isLastWhiteSpace or isLastPunctChar)) + ) + right_flanking = not ( + isLastWhiteSpace + or (isLastPunctChar and not (isNextWhiteSpace or isNextPunctChar)) + ) + + can_open = left_flanking and ( + canSplitWord or (not right_flanking) or isLastPunctChar + ) + can_close = right_flanking and ( + canSplitWord or (not left_flanking) or isNextPunctChar + ) + + return Scanned(can_open, can_close, count) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/strikethrough.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/strikethrough.py new file mode 100644 index 0000000000000000000000000000000000000000..ec816281d49b23d0774bf91db6600d996aaf8b06 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/strikethrough.py @@ -0,0 +1,127 @@ +# ~~strike through~~ +from __future__ import annotations + +from .state_inline import Delimiter, StateInline + + +def tokenize(state: StateInline, silent: bool) -> bool: + """Insert each marker as a separate text token, and add it to delimiter list""" + start = state.pos + ch = state.src[start] + + if silent: + return False + + if ch != "~": + return False + + scanned = state.scanDelims(state.pos, True) + length = scanned.length + + if length < 2: + return False + + if length % 2: + token = state.push("text", "", 0) + token.content = ch + length -= 1 + + i = 0 + while i < length: + token = state.push("text", "", 0) + token.content = ch + ch + state.delimiters.append( + Delimiter( + marker=ord(ch), + length=0, # disable "rule of 3" length checks meant for emphasis + token=len(state.tokens) - 1, + end=-1, + open=scanned.can_open, + close=scanned.can_close, + ) + ) + + i += 2 + + state.pos += scanned.length + + return True + + +def _postProcess(state: StateInline, delimiters: list[Delimiter]) -> None: + loneMarkers = [] + maximum = len(delimiters) + + i = 0 + while i < maximum: + startDelim = delimiters[i] + + if startDelim.marker != 0x7E: # /* ~ */ + i += 1 + continue + + if startDelim.end == -1: + i += 1 + continue + + endDelim = delimiters[startDelim.end] + + token = state.tokens[startDelim.token] + token.type = "s_open" + token.tag = "s" + token.nesting = 1 + token.markup = "~~" + token.content = "" + + token = state.tokens[endDelim.token] + token.type = "s_close" + token.tag = "s" + token.nesting = -1 + token.markup = "~~" + token.content = "" + + if ( + state.tokens[endDelim.token - 1].type == "text" + and state.tokens[endDelim.token - 1].content == "~" + ): + loneMarkers.append(endDelim.token - 1) + + i += 1 + + # If a marker sequence has an odd number of characters, it's split + # like this: `~~~~~` -> `~` + `~~` + `~~`, leaving one marker at the + # start of the sequence. + # + # So, we have to move all those markers after subsequent s_close tags. + # + while loneMarkers: + i = loneMarkers.pop() + j = i + 1 + + while (j < len(state.tokens)) and (state.tokens[j].type == "s_close"): + j += 1 + + j -= 1 + + if i != j: + token = state.tokens[j] + state.tokens[j] = state.tokens[i] + state.tokens[i] = token + + +def postProcess(state: StateInline) -> None: + """Walk through delimiter list and replace text tokens with tags.""" + tokens_meta = state.tokens_meta + maximum = len(state.tokens_meta) + _postProcess(state, state.delimiters) + + curr = 0 + while curr < maximum: + try: + curr_meta = tokens_meta[curr] + except IndexError: + pass + else: + if curr_meta and "delimiters" in curr_meta: + _postProcess(state, curr_meta["delimiters"]) + curr += 1 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/text.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/text.py new file mode 100644 index 0000000000000000000000000000000000000000..18b2fcc7a8f5a40d4820df53838d29fcce833f3f --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it/rules_inline/text.py @@ -0,0 +1,62 @@ +import functools +import re + +# Skip text characters for text token, place those to pending buffer +# and increment current pos +from .state_inline import StateInline + +# Rule to skip pure text +# '{}$%@~+=:' reserved for extensions + +# !!!! Don't confuse with "Markdown ASCII Punctuation" chars +# http://spec.commonmark.org/0.15/#ascii-punctuation-character + + +_TerminatorChars = { + "\n", + "!", + "#", + "$", + "%", + "&", + "*", + "+", + "-", + ":", + "<", + "=", + ">", + "@", + "[", + "\\", + "]", + "^", + "_", + "`", + "{", + "}", + "~", +} + + +@functools.cache +def _terminator_char_regex() -> re.Pattern[str]: + return re.compile("[" + re.escape("".join(_TerminatorChars)) + "]") + + +def text(state: StateInline, silent: bool) -> bool: + pos = state.pos + posMax = state.posMax + + terminator_char = _terminator_char_regex().search(state.src, pos) + pos = terminator_char.start() if terminator_char else posMax + + if pos == state.pos: + return False + + if not silent: + state.pending += state.src[state.pos : pos] + + state.pos = pos + + return True diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it_py-4.0.0.dist-info/licenses/LICENSE b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it_py-4.0.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..582ddf59e08277fe6e78cee924d2c84805fe36fe --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it_py-4.0.0.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 ExecutableBookProject + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it_py-4.0.0.dist-info/licenses/LICENSE.markdown-it b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it_py-4.0.0.dist-info/licenses/LICENSE.markdown-it new file mode 100644 index 0000000000000000000000000000000000000000..7ffa058cb78f8fb9beb974d9fd429004d2d2e585 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/markdown_it_py-4.0.0.dist-info/licenses/LICENSE.markdown-it @@ -0,0 +1,22 @@ +Copyright (c) 2014 Vitaly Puzrin, Alex Kocharin. + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdown_extensions-10.16.1.dist-info/licenses/LICENSE.md b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdown_extensions-10.16.1.dist-info/licenses/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..214b53b26ac4bde95c5675bb35db8892918e677b --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdown_extensions-10.16.1.dist-info/licenses/LICENSE.md @@ -0,0 +1,113 @@ +# License + +## PyMdown Extensions + +The MIT License (MIT) + +Copyright (c) 2014 - 2025 Isaac Muse + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +## SuperFences + +`superfences.py` is derived from Python Markdown's fenced_code extension. + +``` +Fenced Code Extension for Python Markdown + ========================================= +This extension adds Fenced Code Blocks to Python-Markdown. +See +for documentation. +Original code Copyright 2007-2008 [Waylan Limberg](http://achinghead.com/). +All changes Copyright 2008-2014 The Python Markdown Project +License: [BSD](http://www.opensource.org/licenses/bsd-license.php) +``` + +## Highlight + +`highlight.py` is derived from Python Markdown's CodeHilite extension. + +``` +CodeHilite Extension for Python-Markdown + ======================================== +Adds code/syntax highlighting to standard Python-Markdown code blocks. +See +for documentation. +Original code Copyright 2006-2008 [Waylan Limberg](http://achinghead.com/). +All changes Copyright 2008-2014 The Python Markdown Project +License: [BSD](http://www.opensource.org/licenses/bsd-license.php) +``` + +## FancyLists + +`fancylists.py` is derived from Python Markdown's list handler. + +``` +Started by Manfred Stienstra (http://www.dwerg.net/). +Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org). +Currently maintained by Waylan Limberg (https://github.com/waylan), +Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser). + +Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later) +Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b) +Copyright 2004 Manfred Stienstra (the original version) + +License: [BSD](http://www.opensource.org/licenses/bsd-license.php) +``` + +## Gemoji Index + +`gemoji_db.py` is generated from Gemoji's source code: @github/gemoji. + +``` +Copyright (c) 2013 GitHub, Inc. + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. +``` + +## EmojiOne Index + +`emoji1_db.py` is generated from EmojiOne's source code: @Ranks/emojione + +``` +EmojiOne Non-Artwork + +Applies to the JavaScript, JSON, PHP, CSS, HTML files, and everything else not covered under the artwork license above. +License: MIT +Complete Legal Terms: http://opensource.org/licenses/MIT +``` diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f08037f75d20af50df87f190487164e0992c7e9 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/__meta__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/__meta__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec5398a1c2bf20248643ddff110c9eaf6a095bcb Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/__meta__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/_bypassnorm.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/_bypassnorm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08d7408028f5768396c596a8f2459bb7e7789013 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/_bypassnorm.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/arithmatex.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/arithmatex.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1e5d878e86d45ea5ebc1d8898241c0cbc6676e2 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/arithmatex.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/b64.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/b64.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4dcf7fa0a29989fd748dd7244243499b7e2d1a7f Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/b64.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/betterem.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/betterem.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5b76fc4001de42fd3a2aa59e39e5c84ed2d134b Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/betterem.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/caret.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/caret.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..353941ebbaf93c45b5c7e016cc9c4a43273a92c2 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/caret.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/critic.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/critic.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be16d8f43412292009efbd0602d8dde56262996d Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/critic.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/details.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/details.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6eaf0332f3c7d5a70fe93b017e65397b782f6371 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/details.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/emoji.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/emoji.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31103c395b19477026c1bedb160101c75eec2410 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/emoji.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/emoji1_db.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/emoji1_db.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63a49fc79cc08bffbff3bce884160e00f4710e07 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/emoji1_db.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7b18109621454d83f29beff99b85fb0412080d87913ca11a39686d3ba5cc8168 +size 195552 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/escapeall.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/escapeall.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..130f94a666b3daaa862fcd688925f52cc44ad9d0 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/escapeall.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/extra.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/extra.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c60289a86be1345355aed30dbd94998161250092 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/extra.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/fancylists.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/fancylists.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..494605bcf1a44b41354bfcf6fb1abf4f37163251 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/fancylists.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/gemoji_db.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/gemoji_db.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bea5e71bd6422ca0a76963902a33a7e996a0142c --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/gemoji_db.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:537a3af29a24f2a1fe92fc803a8a7824531ff05eb173f9f25e6884c0500c1e18 +size 177016 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/highlight.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/highlight.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0df762020749c1fab1b90a16307bb04410b7e375 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/highlight.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/inlinehilite.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/inlinehilite.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42e6e0fbdee3da089491a1ec6152e3d153fc5aa0 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/inlinehilite.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/keymap_db.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/keymap_db.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9a498fba0e9323beba2ff588c8978cb09a19910 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/keymap_db.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/keys.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/keys.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05c9fa803ba6bf5eded0f5ee33bdfa1a57e6dae1 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/keys.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/magiclink.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/magiclink.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..855320a21b1560626abb231c798d69f377d78a9f Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/magiclink.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/mark.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/mark.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0dd875377fdac9456d16a612df3334d465a93e71 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/mark.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/pathconverter.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/pathconverter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bbf45473c854ee3d6f2090569203c82b1bc3b949 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/pathconverter.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/progressbar.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/progressbar.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa70c7a3c88d7faacb5bc1394843879a49edd5d0 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/progressbar.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/saneheaders.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/saneheaders.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73bd06bd86a6922ebf82691854cb24c029668940 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/saneheaders.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/slugs.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/slugs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0ff3a65f84f3b8bdebd7d61622c151d90ce3915 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/slugs.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/smartsymbols.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/smartsymbols.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa0352d8a36956d6b9b03121555e2a41f83865e1 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/smartsymbols.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/snippets.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/snippets.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae2f5f2624915daf1433834135fed9ae65e719ea Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/snippets.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/striphtml.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/striphtml.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6eb5c34763bb8cc753bb06fe860c0899c734261 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/striphtml.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/superfences.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/superfences.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aafae4385c4e5c8ae60bae05486e55ae16648934 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/superfences.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/tabbed.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/tabbed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cdb014c689ce95e88c7c15f18c04c6782ce7f05e Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/tabbed.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/tasklist.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/tasklist.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a75af98606561fd7065388175f229c214c1721a6 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/tasklist.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/tilde.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/tilde.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71eb2035d054b8709a2ffb857d83936d1ea7f6f5 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/tilde.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/twemoji_db.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/twemoji_db.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a326dd5febe31ac05be0c9bcc758ed362bd58a87 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/twemoji_db.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0f758bd10692a1b0eea43466eb855b295d4ff821aa1e536ba91499d770fa924d +size 585294 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/util.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f03d969aefec6d1127e944f6d3c121fa9760b847 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/__pycache__/util.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..616f697c0edb55557f6e86602caab5d715ff1ceb --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__init__.py @@ -0,0 +1,543 @@ +"""Generic blocks extension.""" +from __future__ import annotations +from markdown import Extension, Markdown +from markdown.blockprocessors import BlockProcessor +from markdown.treeprocessors import Treeprocessor +from markdown.blockparser import BlockParser +from markdown import util as mutil +from .. import util +import xml.etree.ElementTree as etree +import re +import yaml +import textwrap +from typing import cast, Any, TYPE_CHECKING + +if TYPE_CHECKING: # pragma: no cover + from .block import Block + +# Fenced block placeholder for SuperFences +FENCED_BLOCK_RE = re.compile( + r'^([\> ]*){}({}){}$'.format( + mutil.HTML_PLACEHOLDER[0], + mutil.HTML_PLACEHOLDER[1:-1] % r'([0-9]+)', + mutil.HTML_PLACEHOLDER[-1] + ) +) + +# Block start/end +RE_START = re.compile( + r'(?:^|\n)[ ]{0,3}(/{3,})[ ]*([\w-]+)[ ]*(?:\|[ ]*(.*?)[ ]*)?(?:\n|$)' +) + +RE_END = re.compile( + r'(?m)(?:^|\n)[ ]{0,3}(/{3,})[ ]*(?:\n|$)' +) + +# Frontmatter patterns +RE_YAML_START = re.compile(r'(?m)^[ ]{0,3}(-{3})[ ]*(?:\n|$)') + +RE_YAML_END = re.compile( + r'(?m)^[ ]{0,3}(-{3})[ ]*(?:\n|$)' +) + +RE_INDENT_YAML_LINE = re.compile(r'(?m)^(?:[ ]{4,}(?!\s).*?(?:\n|$))+') + + +class BlockEntry: + """Track Block entries.""" + + def __init__(self, block: Block, el: etree.Element, parent: etree.Element) -> None: + """Block entry.""" + + self.block: 'Block' = block + self.el: etree.Element = el + self.parent: etree.Element = parent + self.hungry: bool = False + + +def get_frontmatter(string: str) -> dict[str, Any] | None: + """ + Get frontmatter from string. + + YAML-ish key value pairs. + """ + + frontmatter = None + + try: + frontmatter = yaml.safe_load(string) + if frontmatter is None: + frontmatter = {} + if not isinstance(frontmatter, dict): + frontmatter = None + except Exception: + pass + + return cast('dict[str, Any]', frontmatter) + + +def reindent(text: str, pos: int, level: int) -> list[str]: + """Reindent the code to where it is supposed to be.""" + + indented = [] + for line in text.split('\n'): + index = pos - level + indented.append(line[index:]) + return indented + + +def unescape_markdown(md: Markdown, blocks: list[str], is_raw: bool) -> list[str]: + """Look for SuperFences code placeholders and other HTML stash placeholders and revert them back to plain text.""" + + superfences = None + try: + from ..superfences import SuperFencesBlockPreprocessor + processor = md.preprocessors['fenced_code_block'] + if isinstance(processor, SuperFencesBlockPreprocessor): + superfences = processor.extension # type: ignore[attr-defined] + except Exception: + pass + + new_blocks = [] + for block in blocks: + new_lines = [] + for line in block.split('\n'): + m = FENCED_BLOCK_RE.match(line) + if m: + key = m.group(2) + + # Extract SuperFences content + indent_level = len(m.group(1)) + original = None + if superfences is not None: + original, pos = superfences.stash.get(key, (None, None)) + if original is not None: + code = reindent(original, pos, indent_level) + new_lines.extend(code) + superfences.stash.remove(key) + + # Extract other HTML stashed content + if original is None and is_raw: + index = int(key.split(':')[1]) + if index < len(md.htmlStash.rawHtmlBlocks): + original = md.htmlStash.rawHtmlBlocks[index] + if isinstance(original, etree.Element): + original = etree.tostring(original, encoding='unicode', method='html') + new_lines.append(original) + + # Couldn't find anything to extract + if original is None: # pragma: no cover + new_lines.append(line) + else: + new_lines.append(line) + new_blocks.append('\n'.join(new_lines)) + + return new_blocks + + +class BlocksTreeprocessor(Treeprocessor): + """Blocks tree processor.""" + + def __init__(self, md: Markdown, blocks: BlocksProcessor): + """Initialize.""" + + super().__init__(md) + + self.blocks = blocks + + def run(self, root: etree.Element) -> None: + """Update tab IDs.""" + + while self.blocks.inline_stack: + entry = self.blocks.inline_stack.pop(0) + entry.block.on_inline_end(entry.el) + + +class BlocksProcessor(BlockProcessor): + """Generic block processor.""" + + def __init__(self, parser: BlockParser, md: Markdown) -> None: + """Initialization.""" + + self.md = md + + # The Block classes indexable by name + self.blocks: dict[str, type[Block]] = {} + self.config: dict[str, dict[str, Any]] = {} + self.empty_tags = {'hr',} + self.block_level_tags = set(md.block_level_elements.copy()) + self.block_level_tags.add('html') + + # Block-level tags in which the content only gets span level parsing + self.span_tags = { + 'address', 'dd', 'dt', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'legend', 'li', 'p', 'summary', 'td', 'th' + } + # Block-level tags which never get their content parsed. + self.raw_tags = {'canvas', 'math', 'option', 'pre', 'script', 'style', 'textarea', 'code'} + # Block-level tags in which the content gets parsed as blocks + self.block_tags = set(self.block_level_tags) - (self.span_tags | self.raw_tags | self.empty_tags) + self.span_and_blocks_tags = self.block_tags | self.span_tags + + super().__init__(parser) + + # Persistent storage across a document for blocks + self.trackers: dict[str, dict[str, Any]] = {} + # Currently queued up blocks + self.stack: list[BlockEntry] = [] + # Blocks that should be processed after inline. + self.inline_stack: list[BlockEntry] = [] + # When set, the assigned block is actively parsing blocks. + self.working: BlockEntry | None = None + # Cached the found parent when testing + # so we can quickly retrieve it when running + self.cached_parent: etree.Element | None = None + self.cached_block: tuple['Block', str] | None = None + + # Used during the alpha/beta stage + self.start = RE_START + self.end = RE_END + self.yaml_line = RE_INDENT_YAML_LINE + + def detab_by_length(self, text: str, length: int) -> tuple[str, str]: + """Remove a tab from the front of each line of the given text.""" + + newtext = [] + lines = text.split('\n') + for line in lines: + if line.startswith(' ' * length): + newtext.append(line[length:]) + elif not line.strip(): + newtext.append('') # pragma: no cover + else: + break + if newtext: + return '\n'.join(newtext), '\n'.join(lines[len(newtext):]) + return '\n'.join(lines[len(newtext):]), '' + + def register(self, b: type[Block], config: dict[str, Any]) -> None: + """Register a block.""" + + if b.NAME in self.blocks: + raise ValueError(f'The block name {b.NAME} is already registered!') + self.blocks[b.NAME] = b + self.config[b.NAME] = config + + def test(self, parent: etree.Element, block: str) -> bool: + """Test to see if we should process the block.""" + + # Are we hungry for more? + if self.get_parent(parent) is not None: + return True + + # Is this the start of a new block? + m = self.start.search(block) + if m: + + pre_text = block[:m.start()] if m.start() > 0 else None + + # Create a block object + name = m.group(2).lower() + if name in self.blocks: + generic_block = self.blocks[name](len(m.group(1)), self.trackers[name], self, self.config[name]) + + # Remove first line + block = block[m.end():] + + # Get frontmatter and argument(s) + options, the_rest = self.split_header(block, generic_block.length) + arguments = m.group(3) + + # Options must be valid + status = options is not None + + # Update the config for the Block + if status: + status = generic_block._validate(parent, arguments, **options) # type: ignore[arg-type] + + # Cache the found Block and any remaining content + if status: + self.cached_block = (generic_block, the_rest) + + # Any text before the block should get handled + if pre_text is not None: + self.parser.parseBlocks(parent, [pre_text]) + + return status + return False + + def _reset(self) -> None: + """Reset.""" + + self.stack.clear() + self.inline_stack.clear() + self.working = None + self.trackers = {d: {} for d in self.blocks.keys()} + + def split_end(self, block: str, length: int) -> tuple[str | None, str | None, bool]: + """Search for end and split the blocks while removing the end.""" + + good = None + bad = None + end = False + + # Find the end of the Block + m = None + for match in self.end.finditer(block): + if len(match.group(1)) == length: + m = match + break + + # Separate everything from before the "end" and after + if m: + temp = block[:m.start(0)] + if temp: + good = temp[:-1] if temp.endswith('\n') else temp + end = True + + # Since we found our end, everything after is unwanted + temp = block[m.end(0):] + if temp: + bad = temp + else: + # Gather blocks until we find our end + good = block + + # Send back the new list of blocks to parse and note whether we found our end + return good, bad, end + + def split_header(self, block: str, length: int) -> tuple[dict[str, Any] | None, str]: + """Split, YAML-ish header out.""" + + # Search for end in first block + m = None + blocks: list[str] = [] + for match in self.end.finditer(block): + if len(match.group(1)) == length: + m = match + break + + # Move block ending to be parsed later + if m: + end = block[m.start(0):] + blocks.insert(0, end) + block = block[:m.start(0)] + + m = self.yaml_line.match(block) + if m is not None: + config = textwrap.dedent(m.group(0)) + blocks.insert(0, block[m.end():]) + if config.strip(): + return get_frontmatter(config), '\n'.join(blocks) + + blocks.insert(0, block) + + return {}, '\n'.join(blocks) + + def get_parent(self, parent: etree.Element) -> etree.Element | None: + """Get parent.""" + + # Returned the cached parent from our last attempt + if self.cached_parent is not None: + parent = self.cached_parent + self.cached_parent = None + return parent + + temp: etree.Element | None = parent + while temp is not None: + if not self.stack: + break + if self.stack[-1].hungry and self.stack[-1].parent is temp: + self.cached_parent = temp + return temp + if temp is not None: + temp = self.lastChild(temp) + return None + + def is_raw(self, tag: etree.Element) -> bool: + """Is tag raw.""" + + return tag.tag in self.raw_tags + + def is_block(self, tag: etree.Element) -> bool: + """Is tag block.""" + + return tag.tag in self.block_tags + + def parse_blocks(self, blocks: list[str], current_parent: etree.Element) -> None: + """Parse the blocks.""" + + # Get the target element and parse + while blocks and self.stack: + b: str | None = blocks.pop(0) + + # Get the latest block on the stack + # This is required to avoid some issues with `md_in_html` + entry = self.stack[-1] + target = entry.block.on_add(entry.el) + + # Since we are juggling the block parsers on the stack, the pipeline + # has not fully adjusted list indentation, so look at how many + # list item parents we have on the stack and adjust the content + # accordingly. + parent_map = {c: p for p in current_parent.iter() for c in p} + # Only need to count lists between nested blocks + parent = self.stack[-1].el if len(self.stack) > 1 else None + li = 0 + while parent is not None: + parent = parent_map.get(parent, None) + if parent is not None: + if parent.tag in ('li', 'dd'): + li += 1 + continue + break + + b, a = self.detab_by_length(cast(str, b), li * self.tab_length) + if a: + blocks.insert(0, a) + + # Split out blocks we care about + b, bad, end = self.split_end(b, entry.block.length) + if bad is not None: + blocks.insert(0, bad) + + # Parse the block under the given target + if b is not None and target is not None: + # Resolve modes + mode = entry.block.on_markdown() + if mode not in ('block', 'inline', 'raw'): + mode = 'auto' + is_block = mode == 'block' or (mode == 'auto' and self.is_block(target)) + is_atomic = mode == 'raw' or (mode == 'auto' and self.is_raw(target)) + + # We should revert fenced code in spans or atomic tags. + # Make sure atomic tags have content wrapped as `AtomicString`. + if is_atomic or not is_block: + child = list(target)[-1] if len(target) else None + text = target.text if child is None else child.tail + b = '\n\n'.join(unescape_markdown(self.md, [b], is_atomic)).strip('\n') + + if text: + text += b if not b else '\n\n' + b + else: + text = b + + if child is None: + target.text = mutil.AtomicString(text) if is_atomic else text + else: # pragma: no cover + # TODO: We would need to build a special plugin to test this, + # as none of the default ones do this, but we have verified this + # locally. Once we've written a test, we can remove this. + child.tail = mutil.AtomicString(text) if is_atomic else text + + # Block tags should have content go through the normal block processor + else: + self.parser.state.set('blocks') + working = self.working + self.working = entry + self.parser.parseChunk(target, b) + self.parser.state.reset() + self.working = working + + # Run "on end" event when we finish a block + if end: + entry.block._end(entry.el) + self.inline_stack.append(entry) + del self.stack[-1] + + # The Block does not or no longer accepts more content + if target is None: # pragma: no cover + break + + if self.stack: + self.stack[-1].hungry = True + + def run(self, parent: etree.Element, blocks: list[str]) -> None: + """Convert to details/summary block.""" + + # Get the appropriate parent for this Block + temp = self.get_parent(parent) + if temp is not None: + parent = temp + + # Did we find a new Block? + if self.cached_block: + # Get cached Block and reset the cache + generic_block, block = self.cached_block + self.cached_block = None + + # Discard first block as we've already processed what we need from it + blocks.pop(0) + if block: + blocks.insert(0, block) + + # Ensure a "tight" parent list item is converted to "loose". + if parent is not None and parent.tag in ('li', 'dd'): # pragma: no cover + text = parent.text + if parent.text: + parent.text = '' + p = etree.SubElement(parent, 'p') + p.text = text + + # Create the block element + el = generic_block._create(parent) + + # Push a Block entry on the stack. + self.stack.append(BlockEntry(generic_block, el, parent)) + + # Parse the text blocks under the Block + self.parse_blocks(blocks, parent) + + else: + for r in range(len(self.stack)): + entry = self.stack[r] + if entry.hungry and parent is entry.parent: + # Get the target element and parse + entry.hungry = False + self.parse_blocks(blocks, parent) + + break + + +class BlocksMgrExtension(Extension): + """Add generic Blocks extension.""" + + def extendMarkdown(self, md: Markdown) -> None: + """Add Blocks to Markdown instance.""" + + md.registerExtension(self) + util.escape_chars(md, ['/']) + self.extension = BlocksProcessor(md.parser, md) + # We want to be right after list indentations are processed + md.parser.blockprocessors.register(self.extension, "blocks", 89.99) + + tree = BlocksTreeprocessor(md, self.extension) + md.treeprocessors.register(tree, 'blocks_on_inline_end', 19.99) + + def reset(self) -> None: + """Reset.""" + + self.extension._reset() + + +class BlocksExtension(Extension): + """Blocks Extension.""" + + def register_block_mgr(self, md: Markdown) -> BlocksProcessor: + """Add Blocks to Markdown instance.""" + + if 'blocks' not in md.parser.blockprocessors: + ext = BlocksMgrExtension() + ext.extendMarkdown(md) + mgr = ext.extension + else: + mgr = cast('BlocksProcessor', md.parser.blockprocessors['blocks']) + return mgr + + def extendMarkdown(self, md: Markdown) -> None: + """Extend markdown.""" + + mgr = self.register_block_mgr(md) + self.extendMarkdownBlocks(md, mgr) + + def extendMarkdownBlocks(self, md: Markdown, block_mgr: BlocksProcessor) -> None: + """Extend Markdown blocks.""" diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c29280797f84c75b09ccd7f0f392cc4a699d5d0 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__pycache__/admonition.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__pycache__/admonition.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ab1865574eab96ed7d99e6fd7444b2b5783e30c Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__pycache__/admonition.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__pycache__/block.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__pycache__/block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4208e19fc3daa5bbe4a919fffca0e1c196559d8b Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__pycache__/block.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__pycache__/caption.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__pycache__/caption.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e1f177b6d2c4b4d6071b140c1ed344b7229a68c Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__pycache__/caption.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__pycache__/definition.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__pycache__/definition.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..436463537e7d7e690a7205c6b594315181c0a65d Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__pycache__/definition.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__pycache__/details.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__pycache__/details.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb0430dc1cd44aa3e299cb4b3dbf79cde3bb3ff0 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__pycache__/details.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__pycache__/html.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__pycache__/html.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ff1eeffee5bfde4ee94a32fea88f82f5f90a4be Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__pycache__/html.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__pycache__/tab.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__pycache__/tab.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dec8fe0a56779f1feb753d044078b76db1f2bc7d Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/__pycache__/tab.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/admonition.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/admonition.py new file mode 100644 index 0000000000000000000000000000000000000000..2aae63b5fe0afea60deb3eeadfd635700fb0a6a9 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/admonition.py @@ -0,0 +1,125 @@ +"""Admonitions.""" +import xml.etree.ElementTree as etree +from .block import Block, type_html_identifier +from .. blocks import BlocksExtension +import re + +RE_SEP = re.compile(r'[_-]+') + + +class Admonition(Block): + """ + Admonition. + + Arguments (1 optional): + - A title. + + Options: + - `type` (string): Attach a single special class for styling purposes. If more are needed, + use the built-in `attributes` options to apply as many classes as desired. + + Content: + Detail body. + """ + + NAME = 'admonition' + ARGUMENT = None + OPTIONS = { + 'type': ('', type_html_identifier), + } + DEF_TITLE = None + DEF_CLASS = None + + def on_validate(self, parent): + """Handle on validate event.""" + + if self.NAME != 'admonition': + self.options['type'] = {'name': self.NAME} + if self.DEF_TITLE: + self.options['type']['title'] = self.DEF_TITLE + if self.DEF_TITLE: + self.options['type']['class'] = self.DEF_CLASS + return True + + def on_create(self, parent): + """Create the element.""" + + # Set classes + classes = ['admonition'] + obj = self.options['type'] + atype = def_title = class_name = '' + if isinstance(obj, dict): + atype = obj['name'] + class_name = obj.get('class', atype) + def_title = obj.get('title', RE_SEP.sub(' ', class_name).title()) + elif isinstance(obj, str): + atype = obj + class_name = atype + def_title = RE_SEP.sub(' ', atype).title() + + if atype and atype != 'admonition': + classes.append(class_name) + + # Create the admonition + el = etree.SubElement(parent, 'div', {'class': ' '.join(classes)}) + + # Create the title + title = None + if self.argument is None: + if atype: + title = def_title + elif self.argument: + title = self.argument + + if title is not None: + ad_title = etree.SubElement(el, 'p', {'class': 'admonition-title'}) + ad_title.text = title + + return el + + +class AdmonitionExtension(BlocksExtension): + """Admonition Blocks Extension.""" + + def __init__(self, *args, **kwargs): + """Initialize.""" + + self.config = { + "types": [ + ['note', 'attention', 'caution', 'danger', 'error', 'tip', 'hint', 'warning'], + "Generate Admonition block extensions for the given types." + ] + } + + super().__init__(*args, **kwargs) + + def extendMarkdownBlocks(self, md, block_mgr): + """Extend Markdown blocks.""" + + block_mgr.register(Admonition, self.getConfigs()) + + # Generate an admonition subclass based on the given names. + for obj in self.getConfig('types', []): + if isinstance(obj, dict): + name = obj['name'] + class_name = obj.get('class', name) + title = obj.get('title', RE_SEP.sub(' ', class_name).title()) + else: + name = obj + class_name = name + title = RE_SEP.sub(' ', class_name).title() + subclass = RE_SEP.sub('', name).title() + block_mgr.register( + type( + subclass, + (Admonition,), + {'OPTIONS': {}, 'NAME': name, 'DEF_TITLE': title, 'DEF_CLASS': class_name} + ), + {} + ) + + +def makeExtension(*args, **kwargs): + """Return extension.""" + + return AdmonitionExtension(*args, **kwargs) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/block.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/block.py new file mode 100644 index 0000000000000000000000000000000000000000..3e937d8adcddfc25db9357546379fea09585cdfa --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/block.py @@ -0,0 +1,401 @@ +"""Block class.""" +from __future__ import annotations +from abc import ABCMeta, abstractmethod +import functools +import copy +import re +import sys +from markdown import util as mutil +import xml.etree.ElementTree as etree +from typing import Any, Callable, TypeVar, TYPE_CHECKING +from collections.abc import Iterable + +if TYPE_CHECKING: # pragma: no cover + from ..blocks import BlocksProcessor + +RE_IDENT = re.compile( + r''' + (?:(?:-?(?:[^\x00-\x2f\x30-\x40\x5B-\x5E\x60\x7B-\x9f])+|--) + (?:[^\x00-\x2c\x2e\x2f\x3A-\x40\x5B-\x5E\x60\x7B-\x9f])*) + ''', + re.I | re.X +) + +RE_INDENT = re.compile(r'(?m)^([ ]*)[^ \n]') + +RE_DEDENT = re.compile(r'(?m)^([ ]*)($)?') + +_T = TypeVar("_T") + + +def _type_multi(value: Any, types: Iterable[Callable[[Any], _T]] = ()) -> _T: + """Multi types.""" + + for t in types: + try: + return t(value) + except ValueError: # noqa: PERF203 + pass + + raise ValueError(f"Type '{type(value)}' did not match any of the provided types") + + +def type_multi(*args: Callable[[Any], _T]) -> Callable[[Any], _T]: + """Validate a type with multiple type functions.""" + + return functools.partial(_type_multi, types=args) + + +def type_any(value: _T) -> _T: + """Accepts any type.""" + + return value + + +def type_none(value: Any) -> None: + """Ensure type None or fail.""" + + if value is not None: + raise ValueError(f'{type(value)} is not None') + + +def _ranged_number( + value: Any, + minimum: int | float | None, + maximum: int | float | None, + number_type: Callable[[Any], int | float] +) -> int | float: + """Check the range of the given number type.""" + + _value = number_type(value) + if minimum is not None and _value < minimum: + raise ValueError(f'{_value} is not greater than {minimum}') + + if maximum is not None and _value > maximum: + raise ValueError(f'{_value} is not greater than {minimum}') + + return _value + + +def type_number(value: Any) -> int | float: + """Ensure type number or fail.""" + + if not isinstance(value, (float, int)): + raise ValueError(f"Could not convert type {type(value)} to a number") + + return value + + +def type_integer(value: Any) -> int: + """Ensure type integer or fail.""" + + if isinstance(value, int): + return value + + if not isinstance(value, float) or not value.is_integer(): + raise ValueError(f"Could not convert type {type(value)} to an integer") + return int(value) + + +def type_ranged_number(minimum: int | None = None, maximum: int | None = None) -> Callable[[Any], int | float]: + """Ensure typed number is within range.""" + + return functools.partial(_ranged_number, minimum=minimum, maximum=maximum, number_type=type_number) + + +def type_ranged_integer(minimum: int | None = None, maximum: int | None = None) -> Callable[[Any], int | float]: + """Ensured type integer is within range.""" + + return functools.partial(_ranged_number, minimum=minimum, maximum=maximum, number_type=type_integer) + + +def type_boolean(value: Any) -> bool: + """Ensure type boolean or fail.""" + + if not isinstance(value, bool): + raise ValueError(f"Could not convert type {type(value)} to a boolean") + return value + + +type_ternary = type_multi(type_none, type_boolean) + + +def type_string(value: Any) -> str: + """Ensure type string or fail.""" + + if isinstance(value, str): + return value + + raise ValueError(f"Could not convert type {type(value)} to a string") + + +def type_string_insensitive(value: Any) -> str: + """Ensure type string and normalize case.""" + + return type_string(value).lower() + + +def type_html_identifier(value: Any) -> str: + """Ensure type HTML attribute name or fail.""" + + value = type_string(value) + m = RE_IDENT.fullmatch(value) + if m is None: + raise ValueError('A valid attribute name must be provided') + return m.group(0) + + +def _delimiter(string: Any, split: str, string_type: Callable[[Any], str]) -> list[str]: + """Split the string by the delimiter and then parse with the parser.""" + + l = [] + # Ensure input is a string + _string = type_string(string) + for s in _string.split(split): + s = s.strip() + if not s: + continue + # Ensure each part conforms to the desired string type + s = string_type(s) + l.append(s) + return l + + +def _string_in(value: Any, accepted: Iterable[str], string_type: Callable[[Any], str]) -> str: + """Ensure type string is within the accepted values.""" + + _value = string_type(value) + if _value not in accepted: + raise ValueError(f'{_value} not found in {accepted!s}') + return _value + + +def type_string_in(accepted: Iterable[str], insensitive: bool = True) -> Callable[[Any], str]: + """Ensure type string is within the accepted list.""" + + return functools.partial( + _string_in, + accepted=accepted, + string_type=type_string_insensitive if insensitive else type_string + ) + + +def type_string_delimiter(split: str, string_type: Callable[[Any], str] = type_string) -> Callable[[Any], list[str]]: + """String delimiter function.""" + + return functools.partial(_delimiter, split=split, string_type=string_type) + + +def type_html_attribute_dict(value: Any) -> dict[str, str | list[str]]: + """Attribute dictionary.""" + + if not isinstance(value, dict): + raise ValueError('Attributes should be contained within a dictionary') + + attributes = {} + for k, v in value.items(): + k = type_html_identifier(k) + if k.lower() == 'class': + k = 'class' + v = type_html_classes(v) + elif k.lower() == 'id': + k = 'id' + v = type_html_identifier(v) + else: + v = type_string(v) + attributes[k] = v + + return attributes + + +# Ensure class(es) or fail +type_html_classes = type_string_delimiter(' ', type_html_identifier) + + +class Block(metaclass=ABCMeta): + """Block.""" + + # Set to something if argument should be split. + # Arguments will be split and white space stripped. + NAME = '' + + # Instance arguments and options + ARGUMENT: bool | None = False + OPTIONS: dict[str, tuple[Any, Callable[[Any], Any]]] = {} + + def __init__(self, length: int, tracker: Any, block_mgr: BlocksProcessor, config: Any): + """ + Initialize. + + - `length` specifies the length (number of slashes) that the header used + - `tracker` is a persistent storage for the life of the current Markdown page. + It is a dictionary where we can keep references until the parent extension is reset. + - `md` is the Markdown object just in case access is needed to something we + didn't think about. + + """ + + # Setup up the argument and options spec + # Note that `attributes` is handled special and we always override it + self.arg_spec = self.ARGUMENT + self.option_spec = copy.deepcopy(self.OPTIONS) + if 'attrs' in self.option_spec: # pragma: no cover + raise ValueError("'attrs' is a reserved option name and cannot be overriden") + self.option_spec['attrs'] = ({}, type_html_attribute_dict) + + self._block_mgr = block_mgr + self.length = length + self.tracker = tracker + self.md = block_mgr.md + self.arguments: list[Any] = [] + self.options: dict[str, Any] = {} + self.config = config + self.on_init() + + def is_raw(self, tag: etree.Element) -> bool: + """Is raw element.""" + + return self._block_mgr.is_raw(tag) + + def is_block(self, tag: etree.Element) -> bool: # pragma: no cover + """Is block element.""" + + return self._block_mgr.is_block(tag) + + def html_escape(self, text: str) -> str: + """Basic html escaping.""" + + text = text.replace('&', '&') + text = text.replace('<', '<') + text = text.replace('>', '>') + return text + + def dedent(self, text: str, length: int | None = None) -> str: + """Dedent raw text.""" + + if length is None: + length = self.md.tab_length + + min_length = sys.maxsize + for x in RE_INDENT.findall(text): + min_length = min(len(x), min_length) + min_length = min(min_length, length) + + def on_match(m: re.Match[str], l: int = min_length) -> str: + return '' if m.group(2) is not None else m.group(1)[l:] + + return RE_DEDENT.sub(on_match, text) + + def on_init(self) -> None: + """On initialize.""" + + return + + def on_markdown(self) -> str: + """Check how element should be treated by the Markdown parser.""" + + return "auto" + + def _validate(self, parent: etree.Element, arg: Any, **options: Any) -> bool: + """Parse configuration.""" + + # Check argument + if (self.arg_spec is not None and ((arg and not self.arg_spec) or (not arg and self.arg_spec))): + return False + + self.argument = arg + + # Fill in defaults options + spec = self.option_spec + parsed = {} + for k, v in spec.items(): + parsed[k] = v[0] + + # Parse provided options + for k, v in options.items(): + + # Parameter not in spec + if k not in spec: + # Unrecognized parameter name + return False + + # Spec explicitly handles parameter + else: + parser = spec[k][1] + if parser is not None: + try: + v = parser(v) + except Exception: + # Invalid parameter value + return False + parsed[k] = v + + # Add parsed options to options + self.options = parsed + + return self.on_validate(parent) + + def on_validate(self, parent: etree.Element) -> bool: + """ + Handle validation event. + + Run after config parsing completes and allows for the opportunity + to invalidate the block if argument, options, or even the parent + element do not meet certain criteria. + + Return `False` to invalidate the block. + """ + + return True + + @abstractmethod + def on_create(self, parent: etree.Element) -> etree.Element: + """Create the needed element and return it.""" + + def _create(self, parent: etree.Element) -> etree.Element: + """Create the element.""" + + el = self.on_create(parent) + + # Handle general HTML attributes + attrib = el.attrib + for k, v in self.options['attrs'].items(): + if k == 'class': + if k in attrib: + # Don't validate what the developer as already attached + v = type_string_delimiter(' ')(attrib['class']) + v + attrib['class'] = ' '.join(v) + else: + attrib[k] = v + return el + + def _end(self, block: etree.Element) -> None: + """Reached end of the block, dedent raw blocks and call `on_end` hook.""" + + mode = self.on_markdown() + add = self.on_add(block) + if mode == 'raw' or (mode == 'auto' and self.is_raw(add)): + text = add.text if add.text is not None else '' + add.text = mutil.AtomicString(self.dedent(text)) + + self.on_end(block) + + def on_end(self, block: etree.Element) -> None: + """Perform any action on end.""" + + return + + def on_add(self, block: etree.Element) -> etree.Element: + """ + Adjust where the content is added and return the desired element. + + Is there a sub-element where this content should go? + This runs before processing every new block. + """ + + return block + + def on_inline_end(self, block: etree.Element) -> None: + """Perform action on the block after inline parsing.""" + + return diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/caption.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/caption.py new file mode 100644 index 0000000000000000000000000000000000000000..c1f2abd9c375fb089f0be7ce2a75eb841398c03c --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/caption.py @@ -0,0 +1,401 @@ +""" +Captions. + +Captions should be placed after a block, that block will be wrapped in a `figure` +and captions will be inserted either at the end of the figure or at the beginning. +If the preceding block happens to be a `figure`, if no `figcaption` is detected +within, the caption will be injected into that figure instead of wrapping. +Keep in mind that when `md_in_html` is used and raw HTML is used, if `markdown=1` +is not present on the caption, the caption will be invisible to this extension. + +Class, IDs, or other attributes will be attached to the figure, not the caption. + +`types`: + A dictionary with figure type names and prefix templates. A template will be + used depending on whether the current type is assumed or directly specified. +`prepend`: + Will prepend `figcaption` at the start of a `figure` instead of the end. +`auto`: + Will generate IDs and prefixes via the provided template for all figures of + a given type as long as they also define a prefix template. +`auto_level`: + Auto number will not be shown below the given level depth. A value of 0, the + default, disables the feature, 1 would show only auto-generate IDs and + prefixes for the outermost figures with prefixes, etc. This level is only + considered for each figure type individually. + +""" +import xml.etree.ElementTree as etree +from .block import Block, type_html_identifier +from .. blocks import BlocksExtension +from markdown.treeprocessors import Treeprocessor +import re + +RE_FIG_NUM = re.compile(r'^(\^)?([1-9][0-9]*(?:\.[1-9][0-9]*)*)(?= |$)') +RE_SEP = re.compile(r'[_-]+') + + +def update_tag(el, fig_type, fig_num, template, prepend, md): + """Update tag ID and caption prefix.""" + + # Auto add an ID + if 'id' not in el.attrib: + el.attrib['id'] = f'__{fig_type}_' + '_'.join(str(x) for x in fig_num.split('.')) + + # Prefix the caption with a given numbered prefix + if template: + for child in list(el) if prepend else reversed(el): + if child.tag == 'figcaption': + children = list(child) + value = md.htmlStash.store(template.format(fig_num)) + if not len(children) or children[0].tag != 'p': + p = etree.Element('p') + span = etree.SubElement(p, 'span', {'class': 'caption-prefix'}) + span.text = value + p.tail = child.text + child.text = None + child.insert(0, p) + else: + p = children[0] + span = etree.Element('span', {'class': 'caption-prefix'}) + span.text = value + empty = not bool(p.text) + span.tail = (' ' + p.text) if not empty else p.text + p.text = None + p.insert(0, span) + + +class CaptionTreeprocessor(Treeprocessor): + """Caption tree processor.""" + + def __init__(self, md, types, config): + """Initialize.""" + + super().__init__(md) + + self.auto = config['auto'] + self.prepend = config['prepend'] + self.type = '' + self.auto_level = max(0, config['auto_level']) + self.fig_types = types + + def run(self, doc): + """Update caption IDs and prefixes.""" + + parent_map = {c: p for p in doc.iter() for c in p} + last = dict.fromkeys(self.fig_types, 0) + counters = {k: [0] for k in self.fig_types} + fig_type = last_type = self.type + figs = [] + fig_num = '' + + # Calculate the depth and iteration at that depth of the given figure. + for el in doc.iter(): + fig_num = '' + stack = -1 + if el.tag == 'figure': + fig_type = last_type + prepend = False + skip = False + + # Find caption appended or prepended + if '__figure_prepend' in el.attrib: + prepend = True + del el.attrib['__figure_prepend'] + + # Determine figure type + if '__figure_type' in el.attrib: + fig_type = el.attrib['__figure_type'] + figs.append(el) + # See if we have an unknown type or the type has no prefix template. + if fig_type not in self.fig_types or not self.fig_types[fig_type]: + continue + else: + # Found a figure that was not generated by this plugin. + continue + + # Handle a specified relative nesting depth + if '__figure_level' in el.attrib: + stack += int(el.attrib['__figure_level']) + 1 + if self.auto_level and stack >= self.auto_level: + continue + else: + stack += 1 + + current = el + while True: + parent = parent_map.get(current, None) + + # No more parents + if parent is None: + break + + # Check if parent element is a figure of the current type + if parent.tag == 'figure' and parent.attrib['__figure_type'] == fig_type: + # See if position in stack is manually specified + level = '__figure_level' in parent.attrib + if level: + stack += int(parent.attrib['__figure_level']) + 1 + else: + stack += 1 + if level: + el.attrib['__figure_level'] = str(stack + 1) + # Ensure position in stack is not deeper than the specified level + if self.auto_level and stack >= self.auto_level: + skip = True + break + + current = parent + + if skip: + # Parent has been skipped so all children are also skipped + continue + + # Found an appropriate figure at an acceptable depth + if stack > -1: + # Handle a manual number + if '__figure_num' in el.attrib: + fig_num = [int(x) for x in el.attrib['__figure_num'].split('.')] + del el.attrib['__figure_num'] + new_stack = len(fig_num) - 1 + el.attrib['__figure_level'] = new_stack - stack + stack = new_stack + + # Increment counter + l = last[fig_type] + counter = counters[fig_type] + if stack > l: + counter.extend([1] * (stack - l)) + elif stack == l: + counter[stack] += 1 + else: + del counter[stack + 1:] + counter[-1] += 1 + last[fig_type] = stack + last_type = fig_type + + # Determine if manual number is not smaller than existing figure numbers at that depth + if fig_num and fig_num > counter: + counter[:] = fig_num[:] + + # Apply prefix and ID + update_tag( + el, + fig_type, + '.'.join(str(x) for x in counter[:stack + 1]), + self.fig_types.get(fig_type, ''), + prepend, + self.md + ) + + # Clean up attributes + for fig in figs: + del fig.attrib['__figure_type'] + if '__figure_level' in fig.attrib: + del fig.attrib['__figure_level'] + + +class Caption(Block): + """Figure captions.""" + + NAME = '' + PREFIX = '' + CLASSES = '' + ARGUMENT = None + OPTIONS = { + 'type': ('', type_html_identifier) + } + + def on_init(self): + """Initialize.""" + + self.auto = self.config['auto'] + self.prepend = self.config['prepend'] + self.caption = None + self.fig_num = '' + self.level = '' + self.classes = self.CLASSES.split() + + def on_validate(self, parent): + """Handle on validate event.""" + + argument = self.argument + if argument: + if argument.startswith('>'): + self.prepend = False + argument = argument[1:].lstrip() + elif argument.startswith('<'): + self.prepend = True + argument = argument[1:].lstrip() + + m = RE_FIG_NUM.match(argument) + if m: + if m.group(1): + self.level = m.group(2) + else: + self.fig_num = m.group(2) + argument = argument[m.end():].lstrip() + + if argument: + return False + return True + + def on_create(self, parent): + """Create the element.""" + + # Find sibling to add caption to. + fig = None + child = None + children = list(parent) + if children: + child = children[-1] + # Do we have a figure with no caption? + if child.tag == 'figure': + fig = child + for c in list(child): + if c.tag == 'figcaption': + fig = None + break + + # Create a new figure if sibling is not a figure or already has a caption. + # Add sibling to the new figure. + if fig is None: + attrib = {} if not self.classes else {'class': ' '.join(self.classes)} + fig = etree.SubElement(parent, 'figure', attrib) + if child is not None: + fig.append(child) + parent.remove(child) + + # Add classes to existing figure + elif self.CLASSES: + classes = fig.attrib.get('class', '').strip() + if classes: + class_list = classes.split() + for c in self.classes: + if c not in class_list: + classes += " " + c + else: + classes = ' '.join(self.classes) + fig.attrib['class'] = classes + + if self.auto: + fig.attrib['__figure_type'] = self.NAME + if self.level: + fig.attrib['__figure_level'] = self.level + if self.fig_num: + fig.attrib['__figure_num'] = self.fig_num + + # Add caption to the target figure. + if self.prepend: + if self.auto: + fig.attrib['__figure_prepend'] = "1" + self.caption = etree.Element('figcaption') + fig.insert(0, self.caption) + else: + self.caption = etree.SubElement(fig, 'figcaption') + + return fig + + def on_add(self, block): + """Return caption as the target container for content.""" + + return self.caption + + def on_end(self, block): + """Handle explicit, manual prefixes on block end.""" + + prefix = self.PREFIX + if prefix and not self.auto: + # Levels should not be used in manual mode, but if they are, give a generic result. + if self.level: + self.fig_num = '.'.join(['1'] * (int(self.level) + 1)) + if self.fig_num: + update_tag( + block, + self.NAME, + self.fig_num, + prefix, + self.prepend, + self.md + ) + + +class CaptionExtension(BlocksExtension): + """Caption Extension.""" + + def __init__(self, *args, **kwargs): + """Initialize.""" + + self.config = { + "types": [ + [ + 'caption', + { + 'name': 'figure-caption', + 'prefix': 'Figure {}.' + }, + { + 'name': 'table-caption', + 'prefix': 'Table {}.' + } + ], + "Configure types a list of types, each type is a dictionary that defines a 'name' and 'prefix' " + "A template must contain '{}' for numerical insertions unless the template is an empty string " + "which will assume no prefix should be used." + ], + "auto_level": [ + 0, + "Depth of children to add prefixes to - Default: 0" + ], + "auto": [ + True, + "Auto add IDs with prefixes (prefixes are only added if prefix template is defined) - Default: False" + ], + "prepend": [ + False, + "Prepend captions opposed to appending - Default: False" + ] + } + + super().__init__(*args, **kwargs) + + def extendMarkdownBlocks(self, md, block_mgr): + """Extend Markdown blocks.""" + + config = self.getConfigs() + + # Generate an details subclass based on the given names. + types = {} + for obj in config['types']: + if isinstance(obj, dict): + name = obj['name'] + prefix = obj.get('prefix', '') + classes = obj.get('classes', '') + else: + name = obj + prefix = '' + classes = '' + types[name] = prefix + subclass = RE_SEP.sub('', name).title() + block_mgr.register( + type( + subclass, + (Caption,), + { + 'OPTIONS': {}, + 'NAME': name, + 'PREFIX': prefix, + 'CLASSES': classes + } + ), + {'auto_level': config['auto_level'], 'auto': config['auto'], 'prepend': config['prepend']} + ) + + if config['auto']: + md.treeprocessors.register(CaptionTreeprocessor(md, types, config), 'caption-auto', 4) + + +def makeExtension(*args, **kwargs): + """Return extension.""" + + return CaptionExtension(*args, **kwargs) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/definition.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/definition.py new file mode 100644 index 0000000000000000000000000000000000000000..56b61058c16da1e56bf4126eed04001655a3c280 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/definition.py @@ -0,0 +1,65 @@ +"""Definition.""" +import xml.etree.ElementTree as etree +from .block import Block +from ..blocks import BlocksExtension + + +class Definition(Block): + """ + Definition. + + Converts non `ul`, `ol` blocks (ideally `p` tags) into `dt` + and will convert first level `li` elements of `ul` and `ol` + elements to `dd` tags. When done, the `ul`, and `ol` elements + will be removed. + """ + + NAME = 'define' + + def on_create(self, parent): + """Create the element.""" + + return etree.SubElement(parent, 'dl') + + def on_end(self, block): + """Convert non list items to details.""" + + remove = [] + offset = 0 + for i, child in enumerate(list(block)): + if child.tag.lower() in ('dt', 'dd'): + continue + + elif child.tag.lower() not in ('ul', 'ol'): + if child.tag.lower() == 'p': + child.tag = 'dt' + else: + dt = etree.Element('dt') + dt.append(child) + block.insert(i + offset, dt) + block.remove(child) + else: + for li in list(child): + offset += 1 + li.tag = 'dd' + block.insert(i + offset, li) + child.remove(li) + remove.append(child) + + for el in remove: + block.remove(el) + + +class DefinitionExtension(BlocksExtension): + """Definition Blocks Extension.""" + + def extendMarkdownBlocks(self, md, block_mgr): + """Extend Markdown blocks.""" + + block_mgr.register(Definition, self.getConfigs()) + + +def makeExtension(*args, **kwargs): + """Return extension.""" + + return DefinitionExtension(*args, **kwargs) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/details.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/details.py new file mode 100644 index 0000000000000000000000000000000000000000..58677234443eb85ff3ee03cdd04f82f7a5470687 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/details.py @@ -0,0 +1,138 @@ +"""Details.""" +import xml.etree.ElementTree as etree +from .block import Block, type_boolean, type_html_identifier +from ..blocks import BlocksExtension +import re + +RE_SEP = re.compile(r'[_-]+') + + +class Details(Block): + """ + Details. + + Arguments (1 optional): + - A summary. + + Options: + - `open` (boolean): force the details block to be in an open state opposed to collapsed. + - `type` (string): Attach a single special class for styling purposes. If more are needed, + use the built-in `attributes` options to apply as many classes as desired. + + Content: + Detail body. + """ + + NAME = 'details' + + ARGUMENT = None + OPTIONS = { + 'open': (False, type_boolean), + 'type': ('', type_html_identifier) + } + + DEF_TITLE = None + DEF_CLASS = None + + def on_validate(self, parent): + """Handle on validate event.""" + + if self.NAME != 'details': + self.options['type'] = {'name': self.NAME} + if self.DEF_TITLE: + self.options['type']['title'] = self.DEF_TITLE + if self.DEF_TITLE: + self.options['type']['class'] = self.DEF_CLASS + return True + + def on_create(self, parent): + """Create the element.""" + + # Is it open? + attributes = {} + if self.options['open']: + attributes['open'] = 'open' + + # Set classes + obj = self.options['type'] + dtype = def_title = class_name = '' + if isinstance(obj, dict): + dtype = obj['name'] + class_name = obj.get('class', dtype) + def_title = obj.get('title', RE_SEP.sub(' ', class_name).title()) + elif isinstance(obj, str): + dtype = obj + class_name = dtype + def_title = RE_SEP.sub(' ', class_name).title() + if dtype: + attributes['class'] = class_name + + # Create Detail element + el = etree.SubElement(parent, 'details', attributes) + + # Create the summary + summary = None + if self.argument is None: + if dtype: + summary = def_title + elif self.argument: + summary = self.argument + + # Create the summary + if summary is not None: + s = etree.SubElement(el, 'summary') + s.text = summary + + return el + + +class DetailsExtension(BlocksExtension): + """Admonition Blocks Extension.""" + + def __init__(self, *args, **kwargs): + """Initialize.""" + + self.config = { + "types": [ + [], + "Generate Admonition block extensions for the given types." + ] + } + + super().__init__(*args, **kwargs) + + def extendMarkdownBlocks(self, md, block_mgr): + """Extend Markdown blocks.""" + + block_mgr.register(Details, self.getConfigs()) + + # Generate an details subclass based on the given names. + for obj in self.getConfig('types', []): + if isinstance(obj, dict): + name = obj['name'] + class_name = obj.get('class', name) + title = obj.get('title', RE_SEP.sub(' ', class_name).title()) + else: + name = obj + class_name = name + title = RE_SEP.sub(' ', class_name).title() + subclass = RE_SEP.sub('', name).title() + block_mgr.register( + type( + subclass, + (Details,), + { + 'OPTIONS': {'open': [False, type_boolean]}, + 'NAME': name, + 'DEF_TITLE': title, + 'DEF_CLASS': class_name + } + ), + {} + ) + + +def makeExtension(*args, **kwargs): + """Return extension.""" + + return DetailsExtension(*args, **kwargs) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/html.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/html.py new file mode 100644 index 0000000000000000000000000000000000000000..27d46b4073742594d19de8be677a7d34f81dc0d7 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/html.py @@ -0,0 +1,213 @@ +"""HTML.""" +import xml.etree.ElementTree as etree +from .block import Block, type_string_in +from ..blocks import BlocksExtension +import re + +# Sub-patterns parts +# Whitespace +WS = r'(?:[ \t])' +# CSS escapes +CSS_ESCAPES = fr'(?:\\(?:[a-f0-9]{{1,6}}{WS}?|[^\r\n\f]|$))' +# CSS Identifier +IDENTIFIER = r''' +(?:(?:-?(?:[^\x00-\x2f\x30-\x40\x5B-\x5E\x60\x7B-\x9f])+|--) +(?:[^\x00-\x2c\x2e\x2f\x3A-\x40\x5B-\x5E\x60\x7B-\x9f])*) +''' +# Value: quoted string or identifier +VALUE = r''' +(?:"(?:\\(?:.)|[^\\"\r\n\f]+)*?"|'(?:\\(?:.)|[^\\'\r\n\f]+)*?'|{ident}+) +'''.format(ident=IDENTIFIER) +# Attribute value comparison. +ATTR = r''' +(?:{ws}*(?P=){ws}*(?P{value}))? +'''.format(ws=WS, value=VALUE) +# Selector patterns +# IDs (`#id`) +PAT_ID = fr'\#{IDENTIFIER}' +# Classes (`.class`) +PAT_CLASS = fr'\.{IDENTIFIER}' +# Attributes (`[attr]`, `[attr=value]`, etc.) +PAT_ATTR = r''' +\[(?:{ws}*(?P{ident}){attr})+{ws}*\] +'''.format(ws=WS, ident=IDENTIFIER, attr=ATTR) + +RE_IDENT = re.compile(IDENTIFIER, flags=re.I | re.X) +RE_ID = re.compile(PAT_ID, flags=re.I | re.X) +RE_CLASS = re.compile(PAT_CLASS, flags=re.I | re.X) +RE_ATTRS = re.compile(PAT_ATTR, flags=re.I | re.X) +RE_ATTR = re.compile(fr'(?P{IDENTIFIER}){ATTR}', flags=re.I | re.X) + +ATTRIBUTES = {'id': RE_ID, 'class': RE_CLASS, 'attr': RE_ATTRS} +VALID_MODES = {'auto', 'inline', 'block', 'raw', 'html'} + + +def parse_selectors(selector): + """Parse the selector.""" + + eol = len(selector) + tag = None + attrs = {} + end = 0 + m = None + + m = RE_IDENT.match(selector) + if m is None: + raise ValueError('No defined tag') + tag = m.group(0) + end = m.end() + + while end < eol: + for atype, pat in ATTRIBUTES.items(): + m = pat.match(selector, end) + if m is not None: + if atype == 'id': + attrs[atype] = m.group(0)[1:] + end = m.end() + elif atype == 'class': + if atype not in attrs: + attrs[atype] = [m.group(0)[1:]] + else: + attrs[atype].append(m.group(0)[1:]) + end = m.end() + else: + results = m.group(0) + m2 = RE_ATTR.search(results) + while m2 is not None: + pos = m2.end() + name = m2.group('attr_name').lower() + value = m2.group('value') + if value is None: + value = name if name != 'class' else '' + elif value.startswith(('"', "'")): + value = value[1:-1] + + if name == 'class': + value = [v for v in value.split(' ') if v] + if value: + if name in attrs: + attrs[name].extend(value) + else: + attrs[name] = value + else: + value = value + attrs[name] = value + m2 = RE_ATTR.search(results, pos) + end = m.end() + break + + if m is None: + raise ValueError('Invalid selector') + + if 'class' in attrs: + attrs['class'] = ' '.join(attrs['class']) + + return tag, attrs + + +class HTML(Block): + """ + HTML. + + Arguments (1 required): + - HTML tag name + + Options: + - `markdown` (string): specify how content inside the element should be treated: + - `auto`: will automatically determine how an element's content should be handled. + - `inline`: treat content as an inline element's content. + - `block`: treat content as a block element's content. + - `raw`: treat the content as raw content (atomic). + + Content: + HTML element content. + """ + + NAME = 'html' + ARGUMENT = True + OPTIONS = { + 'markdown': ('auto', type_string_in(VALID_MODES)) + } + + def __init__(self, length, tracker, md, config): + """Initialize.""" + + self.markdown = None + self.custom = {} + for entry in config.get('custom'): + mode = entry.get('mode', 'auto') + self.custom[entry['tag']] = mode if mode in VALID_MODES else 'auto' + super().__init__(length, tracker, md, config) + + def on_validate(self, parent): + """Handle argument parsing.""" + + try: + self.tag, self.attr = parse_selectors(self.argument) + except ValueError: + return False + + return True + + def on_markdown(self): + """Check if this is atomic.""" + + mode = self.options['markdown'] + if mode == 'auto': + tag = self.tag.lower() + mode = self.custom.get(tag, mode) + + if mode == 'html': + mode = 'raw' + return mode + + def on_create(self, parent): + """Create the element.""" + + # Create element + return etree.SubElement(parent, self.tag.lower(), self.attr) + + def is_html(self, tag): + """Does tag require no processing and no HTML escaping.""" + + return tag.tag in ('script', 'style') + + def on_end(self, block): + """On end event.""" + + mode = self.options['markdown'] + if mode == 'auto': + tag = self.tag.lower() + mode = self.custom.get(tag, mode) + + if (mode == 'auto' and self.is_html(block)) or mode == 'html': + block.text = self.md.htmlStash.store(block.text) + elif (mode == 'auto' and self.is_raw(block)) or mode == 'raw': + block.text = self.md.htmlStash.store(self.html_escape(block.text)) + + +class HTMLExtension(BlocksExtension): + """HTML Blocks Extension.""" + + def __init__(self, *args, **kwargs): + """Initialize.""" + + self.config = { + "custom": [ + [], + "Specify handling for custom blocks." + ] + } + + super().__init__(*args, **kwargs) + + def extendMarkdownBlocks(self, md, block_mgr): + """Extend Markdown blocks.""" + + block_mgr.register(HTML, self.getConfigs()) + + +def makeExtension(*args, **kwargs): + """Return extension.""" + + return HTMLExtension(*args, **kwargs) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/tab.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/tab.py new file mode 100644 index 0000000000000000000000000000000000000000..52042393da972f9f6b901689b08fc59e2e55f916 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pymdownx/blocks/tab.py @@ -0,0 +1,303 @@ +"""Tabs.""" +import xml.etree.ElementTree as etree +from markdown.extensions import toc +from markdown.treeprocessors import Treeprocessor +from .block import Block, type_boolean +from ..blocks import BlocksExtension +import html + +HEADERS = {'h1', 'h2', 'h3', 'h4', 'h5', 'h6'} + + +class TabbedTreeprocessor(Treeprocessor): + """Tab tree processor.""" + + def __init__(self, md, config): + """Initialize.""" + + super().__init__(md) + + self.alternate = config['alternate_style'] + self.slugify = config['slugify'] + self.combine_header_slug = config['combine_header_slug'] + self.sep = config["separator"] + + def get_parent_header_slug(self, root, header_map, parent_map, el): + """Attempt retrieval of parent header slug.""" + + parent = el + last_parent = parent + while parent is not root: + last_parent = parent + parent = parent_map[parent] + if parent in header_map: + headers = header_map[parent] + header = None + for i in list(parent): + if i is el and header is None: + break + if i is last_parent and header is not None: + return header.attrib.get("id", '') + if i in headers: + header = i + return '' + + def run(self, doc): + """Update tab IDs.""" + + # Get a list of id attributes + used_ids = set() + parent_map = {} + header_map = {} + + if self.combine_header_slug: + parent_map = {c: p for p in doc.iter() for c in p} + + for el in doc.iter(): + if "id" in el.attrib: + if self.combine_header_slug and el.tag in HEADERS: + parent = parent_map[el] + if parent in header_map: + header_map[parent].append(el) + else: + header_map[parent] = [el] + used_ids.add(el.attrib["id"]) + + for el in doc.iter(): + if isinstance(el.tag, str) and el.tag.lower() == 'div': + classes = el.attrib.get('class', '').split() + if 'tabbed-set' in classes and (not self.alternate or 'tabbed-alternate' in classes): + inputs = [] + labels = [] + if self.alternate: + for i in list(el): + if i.tag == 'input': + inputs.append(i) + if i.tag == 'div' and i.attrib.get('class', '') == 'tabbed-labels': + labels = [j for j in list(i) if j.tag == 'label'] + else: + for i in list(el): + if i.tag == 'input': + inputs.append(i) + if i.tag == 'label': + labels.append(i) + + # Generate slugged IDs + for inpt, label in zip(inputs, labels): + innerhtml = toc.render_inner_html(toc.remove_fnrefs(label), self.md) + innertext = html.unescape(toc.strip_tags(innerhtml)) + if self.combine_header_slug: + parent_slug = self.get_parent_header_slug(doc, header_map, parent_map, el) + else: + parent_slug = '' + slug = self.slugify(innertext, self.sep) + if parent_slug: + slug = parent_slug + self.sep + slug + slug = toc.unique(slug, used_ids) + inpt.attrib["id"] = slug + label.attrib["for"] = slug + + +class Tab(Block): + """ + Tabbed container. + + Arguments (1 required): + - A tab title. + + Options: + - `new` (boolean): since consecutive tabs are automatically grouped, `new` can force a tab + to start a new tab container. + + Content: + Detail body. + """ + + NAME = 'tab' + + ARGUMENT = True + OPTIONS = { + 'new': (False, type_boolean), + 'select': (False, type_boolean) + } + + def on_init(self): + """Handle initialization.""" + + self.alternate_style = self.config['alternate_style'] + self.slugify = callable(self.config['slugify']) + + # Track tab group count across the entire page. + if 'tab_group_count' not in self.tracker: + self.tracker['tab_group_count'] = 0 + + self.tab_content = None + + def last_child(self, parent): + """Return the last child of an `etree` element.""" + + if len(parent): + return parent[-1] + else: + return None + + def on_add(self, block): + """Adjust where the content is added.""" + + if self.tab_content is None: + if self.alternate_style: + for d in block.findall('div'): + c = d.attrib['class'] + if c == 'tabbed-content' or c.startswith('tabbed-content '): + self.tab_content = list(d)[-1] + break + else: + self.tab_content = list(block)[-1] + + return self.tab_content + + def on_create(self, parent): + """Create the element.""" + + new_group = self.options['new'] + select = self.options['select'] + title = self.argument + sibling = self.last_child(parent) + tabbed_set = 'tabbed-set' if not self.alternate_style else 'tabbed-set tabbed-alternate' + index = 0 + labels = None + content = None + + if ( + sibling is not None and sibling.tag.lower() == 'div' and + sibling.attrib.get('class', '') == tabbed_set and + not new_group + ): + first = False + tab_group = sibling + + if self.alternate_style: + index = [index for index, _ in enumerate(tab_group.findall('input'), 1)][-1] + for d in tab_group.findall('div'): + if d.attrib['class'] == 'tabbed-labels': + labels = d + elif d.attrib['class'] == 'tabbed-content': + content = d + if labels is not None and content is not None: + break + else: + first = True + self.tracker['tab_group_count'] += 1 + tab_group = etree.SubElement( + parent, + 'div', + {'class': tabbed_set, 'data-tabs': '%d:0' % self.tracker['tab_group_count']} + ) + + if self.alternate_style: + labels = etree.SubElement( + tab_group, + 'div', + {'class': 'tabbed-labels'} + ) + content = etree.SubElement( + tab_group, + 'div', + {'class': 'tabbed-content'} + ) + + data = tab_group.attrib['data-tabs'].split(':') + tab_set = int(data[0]) + tab_count = int(data[1]) + 1 + + attributes = { + "name": "__tabbed_%d" % tab_set, + "type": "radio" + } + + if not self.slugify: + attributes['id'] = "__tabbed_%d_%d" % (tab_set, tab_count) + + attributes2 = {"for": "__tabbed_%d_%d" % (tab_set, tab_count)} if not self.slugify else {} + + if first or select: + attributes['checked'] = 'checked' + # Remove any previously assigned "checked states" to siblings + for i in tab_group.findall('input'): + if i.attrib.get('name', '') == f'__tabbed_{tab_set}': + if 'checked' in i.attrib: + del i.attrib['checked'] + + if self.alternate_style: + input_el = etree.Element( + 'input', + attributes + ) + tab_group.insert(index, input_el) + lab = etree.SubElement( + labels, + "label", + attributes2 + ) + lab.text = title + + attrib = {'class': 'tabbed-block'} + etree.SubElement( + content, + "div", + attrib + ) + else: + etree.SubElement( + tab_group, + 'input', + attributes + ) + lab = etree.SubElement( + tab_group, + "label", + attributes2 + ) + lab.text = title + + etree.SubElement( + tab_group, + "div", + { + "class": "tabbed-content" + } + ) + + tab_group.attrib['data-tabs'] = '%d:%d' % (tab_set, tab_count) + + return tab_group + + +class TabExtension(BlocksExtension): + """Admonition Blocks Extension.""" + + def __init__(self, *args, **kwargs): + """Initialize.""" + + self.config = { + 'alternate_style': [False, "Use alternate style - Default: False"], + 'slugify': [0, "Slugify function used to create tab specific IDs - Default: None"], + 'combine_header_slug': [False, "Combine the tab slug with the slug of the parent header - Default: False"], + 'separator': ['-', "Slug separator - Default: '-'"] + } + + super().__init__(*args, **kwargs) + + def extendMarkdownBlocks(self, md, block_mgr): + """Extend Markdown blocks.""" + + block_mgr.register(Tab, self.getConfigs()) + if callable(self.getConfig('slugify')): + slugs = TabbedTreeprocessor(md, self.getConfigs()) + md.treeprocessors.register(slugs, 'tab_slugs', 4) + + +def makeExtension(*args, **kwargs): + """Return extension.""" + + return TabExtension(*args, **kwargs) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pytest/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pytest/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6178c7925756d348afc70b5739bc5bf637dc059 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pytest/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/pytest/__pycache__/__main__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pytest/__pycache__/__main__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bd17a77d71a9ca3191fa78b89ed712ed1c00128 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/pytest/__pycache__/__main__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/scylla_driver-3.29.4.dist-info/licenses/LICENSE b/platform/dataops/dto/.venv/lib/python3.12/site-packages/scylla_driver-3.29.4.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f433b1a53f5b830a205fd2df78e2b34974656c7b --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/scylla_driver-3.29.4.dist-info/licenses/LICENSE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS