avrae-ls 0.4.0__tar.gz → 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. avrae_ls-0.5.0/.gitignore +212 -0
  2. {avrae_ls-0.4.0/src/avrae_ls.egg-info → avrae_ls-0.5.0}/PKG-INFO +31 -11
  3. {avrae_ls-0.4.0 → avrae_ls-0.5.0}/pyproject.toml +11 -9
  4. avrae_ls-0.4.0/PKG-INFO +0 -86
  5. avrae_ls-0.4.0/setup.cfg +0 -4
  6. avrae_ls-0.4.0/src/avrae_ls/__init__.py +0 -3
  7. avrae_ls-0.4.0/src/avrae_ls/__main__.py +0 -108
  8. avrae_ls-0.4.0/src/avrae_ls/alias_preview.py +0 -180
  9. avrae_ls-0.4.0/src/avrae_ls/api.py +0 -2014
  10. avrae_ls-0.4.0/src/avrae_ls/argparser.py +0 -430
  11. avrae_ls-0.4.0/src/avrae_ls/argument_parsing.py +0 -67
  12. avrae_ls-0.4.0/src/avrae_ls/completions.py +0 -984
  13. avrae_ls-0.4.0/src/avrae_ls/config.py +0 -496
  14. avrae_ls-0.4.0/src/avrae_ls/context.py +0 -229
  15. avrae_ls-0.4.0/src/avrae_ls/cvars.py +0 -115
  16. avrae_ls-0.4.0/src/avrae_ls/diagnostics.py +0 -694
  17. avrae_ls-0.4.0/src/avrae_ls/dice.py +0 -33
  18. avrae_ls-0.4.0/src/avrae_ls/parser.py +0 -44
  19. avrae_ls-0.4.0/src/avrae_ls/runtime.py +0 -661
  20. avrae_ls-0.4.0/src/avrae_ls/server.py +0 -390
  21. avrae_ls-0.4.0/src/avrae_ls/signature_help.py +0 -201
  22. avrae_ls-0.4.0/src/avrae_ls/symbols.py +0 -266
  23. avrae_ls-0.4.0/src/avrae_ls.egg-info/SOURCES.txt +0 -48
  24. avrae_ls-0.4.0/src/avrae_ls.egg-info/dependency_links.txt +0 -1
  25. avrae_ls-0.4.0/src/avrae_ls.egg-info/entry_points.txt +0 -2
  26. avrae_ls-0.4.0/src/avrae_ls.egg-info/requires.txt +0 -10
  27. avrae_ls-0.4.0/src/avrae_ls.egg-info/top_level.txt +0 -2
  28. avrae_ls-0.4.0/src/draconic/__init__.py +0 -4
  29. avrae_ls-0.4.0/src/draconic/exceptions.py +0 -157
  30. avrae_ls-0.4.0/src/draconic/helpers.py +0 -236
  31. avrae_ls-0.4.0/src/draconic/interpreter.py +0 -1091
  32. avrae_ls-0.4.0/src/draconic/string.py +0 -100
  33. avrae_ls-0.4.0/src/draconic/types.py +0 -364
  34. avrae_ls-0.4.0/src/draconic/utils.py +0 -78
  35. avrae_ls-0.4.0/src/draconic/versions.py +0 -4
  36. avrae_ls-0.4.0/tests/test_alias_preview.py +0 -96
  37. avrae_ls-0.4.0/tests/test_api.py +0 -105
  38. avrae_ls-0.4.0/tests/test_argparser_unit.py +0 -42
  39. avrae_ls-0.4.0/tests/test_argument_parsing.py +0 -11
  40. avrae_ls-0.4.0/tests/test_completions.py +0 -226
  41. avrae_ls-0.4.0/tests/test_config_env.py +0 -65
  42. avrae_ls-0.4.0/tests/test_cvars.py +0 -61
  43. avrae_ls-0.4.0/tests/test_diagnostics.py +0 -236
  44. avrae_ls-0.4.0/tests/test_gvars.py +0 -84
  45. avrae_ls-0.4.0/tests/test_hover.py +0 -149
  46. avrae_ls-0.4.0/tests/test_runtime.py +0 -563
  47. avrae_ls-0.4.0/tests/test_runtime_dice.py +0 -37
  48. avrae_ls-0.4.0/tests/test_symbols.py +0 -112
  49. {avrae_ls-0.4.0 → avrae_ls-0.5.0}/LICENSE +0 -0
  50. {avrae_ls-0.4.0 → avrae_ls-0.5.0}/README.md +0 -0
  51. {avrae_ls-0.4.0 → avrae_ls-0.5.0}/src/draconic/LICENSE +0 -0
@@ -0,0 +1,212 @@
1
+ # Created by https://www.toptal.com/developers/gitignore/api/python,linux,visualstudiocode
2
+ # Edit at https://www.toptal.com/developers/gitignore?templates=python,linux,visualstudiocode
3
+
4
+ ### Linux ###
5
+ *~
6
+
7
+ # temporary files which can be created if a process still has a handle open of a deleted file
8
+ .fuse_hidden*
9
+
10
+ # KDE directory preferences
11
+ .directory
12
+
13
+ # Linux trash folder which might appear on any partition or disk
14
+ .Trash-*
15
+
16
+ # .nfs files are created when an open file is removed but is still being accessed
17
+ .nfs*
18
+
19
+ ### Python ###
20
+ # Byte-compiled / optimized / DLL files
21
+ __pycache__/
22
+ *.py[cod]
23
+ *$py.class
24
+
25
+ # C extensions
26
+ *.so
27
+
28
+ # Distribution / packaging
29
+ .Python
30
+ build/
31
+ develop-eggs/
32
+ dist/
33
+ downloads/
34
+ eggs/
35
+ .eggs/
36
+ lib/
37
+ lib64/
38
+ parts/
39
+ sdist/
40
+ var/
41
+ wheels/
42
+ share/python-wheels/
43
+ *.egg-info/
44
+ .installed.cfg
45
+ *.egg
46
+ MANIFEST
47
+
48
+ # PyInstaller
49
+ # Usually these files are written by a python script from a template
50
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
51
+ *.manifest
52
+ *.spec
53
+
54
+ # Installer logs
55
+ pip-log.txt
56
+ pip-delete-this-directory.txt
57
+
58
+ # Unit test / coverage reports
59
+ htmlcov/
60
+ .tox/
61
+ .nox/
62
+ .coverage
63
+ .coverage.*
64
+ .cache
65
+ nosetests.xml
66
+ coverage.xml
67
+ *.cover
68
+ *.py,cover
69
+ .hypothesis/
70
+ .pytest_cache/
71
+ cover/
72
+
73
+ # Translations
74
+ *.mo
75
+ *.pot
76
+
77
+ # Django stuff:
78
+ *.log
79
+ local_settings.py
80
+ db.sqlite3
81
+ db.sqlite3-journal
82
+
83
+ # Flask stuff:
84
+ instance/
85
+ .webassets-cache
86
+
87
+ # Scrapy stuff:
88
+ .scrapy
89
+
90
+ # Sphinx documentation
91
+ docs/_build/
92
+
93
+ # PyBuilder
94
+ .pybuilder/
95
+ target/
96
+
97
+ # Jupyter Notebook
98
+ .ipynb_checkpoints
99
+
100
+ # IPython
101
+ profile_default/
102
+ ipython_config.py
103
+
104
+ # pyenv
105
+ # For a library or package, you might want to ignore these files since the code is
106
+ # intended to run in multiple environments; otherwise, check them in:
107
+ # .python-version
108
+
109
+ # pipenv
110
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
111
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
112
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
113
+ # install all needed dependencies.
114
+ #Pipfile.lock
115
+
116
+ # poetry
117
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
118
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
119
+ # commonly ignored for libraries.
120
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
121
+ #poetry.lock
122
+
123
+ # pdm
124
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
125
+ #pdm.lock
126
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
127
+ # in version control.
128
+ # https://pdm.fming.dev/#use-with-ide
129
+ .pdm.toml
130
+
131
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
132
+ __pypackages__/
133
+
134
+ # Celery stuff
135
+ celerybeat-schedule
136
+ celerybeat.pid
137
+
138
+ # SageMath parsed files
139
+ *.sage.py
140
+
141
+ # Environments
142
+ .env
143
+ .venv
144
+ env/
145
+ venv/
146
+ ENV/
147
+ env.bak/
148
+ venv.bak/
149
+
150
+ # Spyder project settings
151
+ .spyderproject
152
+ .spyproject
153
+
154
+ # Rope project settings
155
+ .ropeproject
156
+
157
+ # mkdocs documentation
158
+ /site
159
+
160
+ # mypy
161
+ .mypy_cache/
162
+ .dmypy.json
163
+ dmypy.json
164
+
165
+ # Pyre type checker
166
+ .pyre/
167
+
168
+ # pytype static type analyzer
169
+ .pytype/
170
+
171
+ # Cython debug symbols
172
+ cython_debug/
173
+
174
+ # PyCharm
175
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
176
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
177
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
178
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
179
+ #.idea/
180
+
181
+ ### Python Patch ###
182
+ # Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
183
+ poetry.toml
184
+
185
+ # ruff
186
+ .ruff_cache/
187
+
188
+ # LSP config files
189
+ pyrightconfig.json
190
+
191
+ ### VisualStudioCode ###
192
+ .vscode/*
193
+ !.vscode/settings.json
194
+ !.vscode/tasks.json
195
+ !.vscode/launch.json
196
+ !.vscode/extensions.json
197
+ !.vscode/*.code-snippets
198
+
199
+ # Local History for Visual Studio Code
200
+ .history/
201
+
202
+ # Built Visual Studio Code Extensions
203
+ *.vsix
204
+
205
+ ### VisualStudioCode Patch ###
206
+ # Ignore all local history of files
207
+ .history
208
+ .ionide
209
+
210
+ # End of https://www.toptal.com/developers/gitignore/api/python,linux,visualstudiocode
211
+ vscode-extension/node_modules/*
212
+ vscode-extension/dist/
@@ -1,21 +1,41 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: avrae-ls
3
- Version: 0.4.0
3
+ Version: 0.5.0
4
4
  Summary: Language server for Avrae draconic aliases
5
5
  Author: 1drturtle
6
- Requires-Python: >=3.11
7
- Description-Content-Type: text/markdown
6
+ License: MIT License
7
+
8
+ Copyright (c) 2025
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
8
27
  License-File: LICENSE
9
- Requires-Dist: pygls>=1.3.1
10
- Requires-Dist: lsprotocol>=2023.0.1
11
- Requires-Dist: httpx>=0.27
28
+ Requires-Python: >=3.11
12
29
  Requires-Dist: d20>=1.1.2
30
+ Requires-Dist: httpx>=0.27
31
+ Requires-Dist: lsprotocol>=2023.0.1
32
+ Requires-Dist: pygls>=1.3.1
13
33
  Provides-Extra: dev
14
- Requires-Dist: pytest>=8.3; extra == "dev"
15
- Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
16
- Requires-Dist: pytest-cov>=7.0.0; extra == "dev"
17
- Requires-Dist: ruff>=0.6; extra == "dev"
18
- Dynamic: license-file
34
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
35
+ Requires-Dist: pytest-cov>=7.0.0; extra == 'dev'
36
+ Requires-Dist: pytest>=8.3; extra == 'dev'
37
+ Requires-Dist: ruff>=0.6; extra == 'dev'
38
+ Description-Content-Type: text/markdown
19
39
 
20
40
  # Avrae Draconic Alias Language Server
21
41
 
@@ -1,15 +1,15 @@
1
1
  [build-system]
2
- requires = ["setuptools>=68", "wheel"]
3
- build-backend = "setuptools.build_meta"
2
+ requires = ["hatchling>=1.21"]
3
+ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "avrae-ls"
7
- version = "0.4.0"
7
+ version = "0.5.0"
8
8
  description = "Language server for Avrae draconic aliases"
9
9
  authors = [
10
10
  { name = "1drturtle" }
11
11
  ]
12
- license-files = ["LICENSE"]
12
+ license = { file = "LICENSE" }
13
13
  readme = "README.md"
14
14
  requires-python = ">=3.11"
15
15
  dependencies = [
@@ -30,8 +30,13 @@ dev = [
30
30
  [project.scripts]
31
31
  avrae-ls = "avrae_ls.__main__:main"
32
32
 
33
- [tool.setuptools.packages.find]
34
- where = ["src"]
33
+ [tool.hatch.build.targets.wheel]
34
+ packages = ["src/avrae_ls", "src/draconic"]
35
+
36
+ [tool.hatch.build]
37
+ include = [
38
+ "src/draconic/LICENSE",
39
+ ]
35
40
 
36
41
  [tool.ruff]
37
42
  line-length = 120
@@ -40,6 +45,3 @@ exclude = [
40
45
  "avrae",
41
46
  "src/draconic"
42
47
  ]
43
-
44
- [tool.setuptools.package-data]
45
- draconic = ["LICENSE"]
avrae_ls-0.4.0/PKG-INFO DELETED
@@ -1,86 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: avrae-ls
3
- Version: 0.4.0
4
- Summary: Language server for Avrae draconic aliases
5
- Author: 1drturtle
6
- Requires-Python: >=3.11
7
- Description-Content-Type: text/markdown
8
- License-File: LICENSE
9
- Requires-Dist: pygls>=1.3.1
10
- Requires-Dist: lsprotocol>=2023.0.1
11
- Requires-Dist: httpx>=0.27
12
- Requires-Dist: d20>=1.1.2
13
- Provides-Extra: dev
14
- Requires-Dist: pytest>=8.3; extra == "dev"
15
- Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
16
- Requires-Dist: pytest-cov>=7.0.0; extra == "dev"
17
- Requires-Dist: ruff>=0.6; extra == "dev"
18
- Dynamic: license-file
19
-
20
- # Avrae Draconic Alias Language Server
21
-
22
- Language Server Protocol (LSP) implementation targeting Avrae-style draconic aliases. It provides syntax/semantic diagnostics, a mocked execution command, and a thin configuration layer driven by a workspace `.avraels.json` file. Credit to Avrae team for all code yoinked!
23
-
24
- ## Install (released package)
25
-
26
- - CLI/server via `uv tool` (preferred): `uv tool install avrae-ls` then `avrae-ls --help` to see stdio/TCP options (same as `python -m avrae_ls`). The VS Code extension uses this invocation by default. The draconic interpreter is vendored, so no Git deps are needed.
27
-
28
- ## VS Code extension (released)
29
-
30
- - Install from VSIX: download `avrae-ls-client.vsix` from the GitHub releases page, then in VS Code run “Extensions: Install from VSIX” and select the file.
31
- - Open your alias workspace; commands like `Avrae: Show Alias Preview` and `Avrae: Run Alias` will be available.
32
-
33
- ## Developing locally
34
-
35
- - Prereqs: [uv](https://github.com/astral-sh/uv) and Node.js.
36
- - Install deps: `uv sync --all-extras` then `make vscode-deps`.
37
- - Build everything locally: `make package` (wheel + VSIX in `dist/`).
38
- - Run tests/lint: `make check`.
39
- - Run via uv tool from source: `uv tool install --from . avrae-ls`.
40
- - Run diagnostics for a single file (stdout + stderr logs): `avrae-ls --analyze path/to/alias.txt --log-level DEBUG`.
41
-
42
- ## How to test
43
-
44
- - Quick check (ruff + pytest): `make check` (uses `uv run ruff` and `uv run pytest` under the hood).
45
- - Lint only: `make lint` or `uv run ruff check src tests`.
46
- - Tests only (with coverage): `make test` or `uv run pytest tests --cov=src`.
47
- - CLI smoke test without installing: `uv run python -m avrae_ls --analyze path/to/alias.txt`.
48
-
49
- ## Runtime differences (mock vs. live Avrae)
50
-
51
- - Mock execution never writes back to Avrae: cvar/uvar/gvar mutations only live for the current run and reset before the next.
52
- - Network is limited to gvar fetches (when `enableGvarFetch` is true) and `verify_signature`; other Avrae/Discord calls are replaced with mocked context data from `.avraels.json`.
53
- - `get_gvar`/`using` values are pulled from local var files first; remote fetches go to `https://api.avrae.io/customizations/gvars/<id>` (or your `avraeService.baseUrl`) using `avraeService.token` and are cached for the session.
54
- - `signature()` returns a mock string (`mock-signature:<int>`). `verify_signature()` POSTs to `/bot/signature/verify`, respects `verifySignatureTimeout`/`verifySignatureRetries`, reuses the last successful response per signature, and includes `avraeService.token` if present.
55
-
56
- ## Troubleshooting gvar fetch / verify_signature
57
-
58
- - `get_gvar` returns `None` or `using(...)` raises `ModuleNotFoundError`: ensure the workspace `.avraels.json` sets `enableGvarFetch: true`, includes a valid `avraeService.token`, or seed the gvar in a var file referenced by `varFiles`.
59
- - HTTP 401/403/404 from fetch/verify calls: check the token (401/403) and the gvar/signature id (404). Override `avraeService.baseUrl` if you mirror the API.
60
- - Slow or flaky calls: tune `verifySignatureTimeout` / `verifySignatureRetries`, or disable remote fetches by flipping `enableGvarFetch` off to rely purely on local vars.
61
-
62
- ## Other editors (stdio)
63
-
64
- - Any client can launch the server with stdio: `avrae-ls --stdio` (flag accepted for client compatibility) or `python -m avrae_ls`. The server will also auto-discover `.avraels.json` in parent folders.
65
- - Neovim (nvim-lspconfig example):
66
- ```lua
67
- require("lspconfig").avraels.setup({
68
- cmd = { "avrae-ls", "--stdio" },
69
- filetypes = { "avrae" },
70
- root_dir = require("lspconfig.util").root_pattern(".avraels.json", ".git"),
71
- })
72
- ```
73
- - Emacs (lsp-mode snippet):
74
- ```elisp
75
- (lsp-register-client
76
- (make-lsp-client
77
- :new-connection (lsp-stdio-connection '("avrae-ls" "--stdio"))
78
- :major-modes '(fundamental-mode) ;; bind to your Avrae alias mode
79
- :server-id 'avrae-ls))
80
- ```
81
- - VS Code commands to mirror: `Avrae: Run Alias (Mock)`, `Avrae: Show Alias Preview`, and `Avrae: Reload Workspace Config` run against the same server binary.
82
-
83
- ## Releasing (maintainers)
84
-
85
- 1. Bump `pyproject.toml` / `package.json`
86
- 2. Create Github release
avrae_ls-0.4.0/setup.cfg DELETED
@@ -1,4 +0,0 @@
1
- [egg_info]
2
- tag_build =
3
- tag_date = 0
4
-
@@ -1,3 +0,0 @@
1
- from .server import create_server
2
-
3
- __all__ = ["create_server"]
@@ -1,108 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import argparse
4
- import asyncio
5
- import logging
6
- import sys
7
- from pathlib import Path
8
- from typing import Iterable
9
-
10
- from lsprotocol import types
11
-
12
- from .config import CONFIG_FILENAME, load_config
13
- from .context import ContextBuilder
14
- from .diagnostics import DiagnosticProvider
15
- from .runtime import MockExecutor
16
- from .server import create_server
17
-
18
-
19
- def main(argv: list[str] | None = None) -> None:
20
- parser = argparse.ArgumentParser(description="Avrae draconic alias language server")
21
- parser.add_argument("--tcp", action="store_true", help="Run in TCP mode instead of stdio")
22
- parser.add_argument("--host", default="127.0.0.1", help="TCP host (when --tcp is set)")
23
- parser.add_argument("--port", type=int, default=2087, help="TCP port (when --tcp is set)")
24
- parser.add_argument("--stdio", action="store_true", help="Accept stdio flag for VS Code clients (ignored)")
25
- parser.add_argument("--log-level", default="WARNING", help="Logging level (DEBUG, INFO, WARNING, ERROR)")
26
- parser.add_argument("--analyze", metavar="FILE", help="Run diagnostics for a file and print them to stdout")
27
- args = parser.parse_args(argv)
28
-
29
- _configure_logging(args.log_level)
30
-
31
- if args.analyze:
32
- if args.tcp:
33
- parser.error("--analyze cannot be combined with --tcp")
34
- sys.exit(_run_analysis(Path(args.analyze)))
35
-
36
- server = create_server()
37
- if args.tcp:
38
- server.start_tcp(args.host, args.port)
39
- else:
40
- server.start_io()
41
-
42
-
43
- def _configure_logging(level: str) -> None:
44
- numeric = getattr(logging, level.upper(), logging.WARNING)
45
- if not isinstance(numeric, int):
46
- numeric = logging.WARNING
47
- logging.basicConfig(
48
- level=numeric,
49
- format="%(levelname)s %(name)s: %(message)s",
50
- )
51
-
52
-
53
- def _run_analysis(path: Path) -> int:
54
- if not path.exists():
55
- print(f"File not found: {path}", file=sys.stderr)
56
- return 2
57
-
58
- workspace_root = _discover_workspace_root(path)
59
- log = logging.getLogger(__name__)
60
- log.info("Analyzing %s (workspace root: %s)", path, workspace_root)
61
-
62
- config, warnings = load_config(workspace_root)
63
- for warning in warnings:
64
- log.warning(warning)
65
-
66
- builder = ContextBuilder(config)
67
- ctx_data = builder.build()
68
- executor = MockExecutor(config.service)
69
- diagnostics = DiagnosticProvider(executor, config.diagnostics)
70
-
71
- source = path.read_text()
72
- results = asyncio.run(diagnostics.analyze(source, ctx_data, builder.gvar_resolver))
73
- _print_diagnostics(path, results)
74
- return 1 if results else 0
75
-
76
-
77
- def _discover_workspace_root(target: Path) -> Path:
78
- current = target if target.is_dir() else target.parent
79
- for folder in [current, *current.parents]:
80
- if (folder / CONFIG_FILENAME).exists():
81
- return folder
82
- return current
83
-
84
-
85
- def _print_diagnostics(path: Path, diagnostics: Iterable[types.Diagnostic]) -> None:
86
- diags = list(diagnostics)
87
- if not diags:
88
- print(f"{path}: no issues found")
89
- return
90
-
91
- for diag in diags:
92
- start = diag.range.start
93
- severity = _severity_label(diag.severity)
94
- source = diag.source or "avrae-ls"
95
- print(f"{path}:{start.line + 1}:{start.character + 1}: {severity} [{source}] {diag.message}")
96
-
97
-
98
- def _severity_label(severity: types.DiagnosticSeverity | None) -> str:
99
- if severity is None:
100
- return "info"
101
- try:
102
- return types.DiagnosticSeverity(severity).name.lower()
103
- except Exception:
104
- return str(severity).lower()
105
-
106
-
107
- if __name__ == "__main__":
108
- main()
@@ -1,180 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import re
4
- import shlex
5
- from dataclasses import dataclass
6
- from typing import Any, Optional, Tuple
7
-
8
- from .parser import DRACONIC_RE
9
- from .runtime import ExecutionResult, MockExecutor
10
- from .context import ContextData, GVarResolver
11
- from .argument_parsing import apply_argument_parsing
12
-
13
-
14
- @dataclass
15
- class RenderedAlias:
16
- command: str
17
- stdout: str
18
- error: Optional[BaseException]
19
- last_value: Any | None = None
20
-
21
-
22
- def _strip_alias_header(text: str) -> str:
23
- lines = text.splitlines()
24
- if lines and lines[0].lstrip().startswith("!alias"):
25
- first = lines[0].lstrip()
26
- parts = first.split(maxsplit=2)
27
- remainder = parts[2] if len(parts) > 2 else ""
28
- body = "\n".join(lines[1:])
29
- if remainder:
30
- return remainder + ("\n" + body if body else "")
31
- return body
32
- return text
33
-
34
-
35
- async def render_alias_command(
36
- text: str,
37
- executor: MockExecutor,
38
- ctx_data: ContextData,
39
- resolver: GVarResolver,
40
- args: list[str] | None = None,
41
- ) -> RenderedAlias:
42
- """Replace <drac2> blocks with their evaluated values and return final command."""
43
- body = _strip_alias_header(text)
44
- body = apply_argument_parsing(body, args)
45
- stdout_parts: list[str] = []
46
- parts: list[str] = []
47
- last_value = None
48
- error: BaseException | None = None
49
-
50
- pos = 0
51
- for match in DRACONIC_RE.finditer(body):
52
- parts.append(body[pos: match.start()])
53
- code = match.group(1)
54
- result: ExecutionResult = await executor.run(code, ctx_data, resolver)
55
- if result.stdout:
56
- stdout_parts.append(result.stdout)
57
- if result.error:
58
- error = result.error
59
- break
60
- last_value = result.value
61
- parts.append("" if result.value is None else str(result.value))
62
- pos = match.end()
63
-
64
- if error is None:
65
- parts.append(body[pos:])
66
-
67
- final_command = "".join(parts)
68
- return RenderedAlias(command=final_command, stdout="".join(stdout_parts), error=error, last_value=last_value)
69
-
70
-
71
- def validate_embed_payload(payload: str) -> Tuple[bool, str | None]:
72
- """
73
- Light validation for embed previews using Avrae-style flags.
74
-
75
- Accepts strings such as "-title Foo -f \"T|Body\"" and validates arguments.
76
- Returns (is_valid, error_message) without attempting to parse JSON objects.
77
- """
78
- text = payload.strip()
79
- if not text:
80
- return False, "Embed payload is empty."
81
-
82
- return _validate_embed_flags(text)
83
-
84
-
85
- def _validate_embed_flags(text: str) -> Tuple[bool, str | None]:
86
- """Validate embed flags according to Avrae's help text."""
87
- if not text:
88
- return False, "Embed payload is empty."
89
-
90
- try:
91
- tokens = shlex.split(text)
92
- except ValueError as exc: # pragma: no cover - defensive only
93
- return False, f"Embed payload could not be parsed: {exc}"
94
-
95
- flag_handlers = {
96
- "-title": lambda val: _require_value("-title", val),
97
- "-desc": lambda val: _require_value("-desc", val),
98
- "-thumb": lambda val: _require_value("-thumb", val),
99
- "-image": lambda val: _require_value("-image", val),
100
- "-footer": lambda val: _require_value("-footer", val),
101
- "-f": _validate_field_arg,
102
- "-color": _validate_color_arg,
103
- "-t": _validate_timeout_arg,
104
- }
105
-
106
- i = 0
107
- while i < len(tokens):
108
- tok = tokens[i]
109
- key = tok.lower()
110
- if not tok.startswith("-"):
111
- i += 1
112
- continue
113
- if key not in flag_handlers:
114
- return False, f"Embed payload contains unknown flag '{tok}'."
115
- next_val = tokens[i + 1] if i + 1 < len(tokens) else None
116
- ok, err, consumed = flag_handlers[key](next_val)
117
- if not ok:
118
- return False, err
119
- i += consumed + 1
120
- return True, None
121
-
122
-
123
- def _require_value(flag: str, value: str | None) -> Tuple[bool, str | None, int]:
124
- if value is None or value.startswith("-"):
125
- return False, f"Embed flag '{flag}' requires a value.", 0
126
- return True, None, 1
127
-
128
-
129
- def _validate_field_arg(value: str | None) -> Tuple[bool, str | None, int]:
130
- ok, err, consumed = _require_value("-f", value)
131
- if not ok:
132
- return ok, err, consumed
133
- assert value is not None # for type checker
134
- parts = value.split("|")
135
- if len(parts) < 2 or len(parts) > 3:
136
- return False, "Embed field must be in the form \"Title|Text[|inline]\".", consumed
137
- if not parts[0] or not parts[1]:
138
- return False, "Embed field title and text cannot be empty.", consumed
139
- if len(parts) == 3 and parts[2].lower() not in ("inline", ""):
140
- return False, "Embed field inline value must be 'inline' or omitted.", consumed
141
- return True, None, consumed
142
-
143
-
144
- def _validate_color_arg(value: str | None) -> Tuple[bool, str | None, int]:
145
- if value is None or value.startswith("-"):
146
- # Random color is allowed when omitted
147
- return True, None, 0
148
- if not re.match(r"^(?:#|0x)?[0-9a-fA-F]{6}$", value):
149
- return False, "Embed color must be a 6-hex value (e.g. #ff00ff).", 1
150
- return True, None, 1
151
-
152
-
153
- def _validate_timeout_arg(value: str | None) -> Tuple[bool, str | None, int]:
154
- ok, err, consumed = _require_value("-t", value)
155
- if not ok:
156
- return ok, err, consumed
157
- assert value is not None # for type checker
158
- try:
159
- num = int(value)
160
- except ValueError:
161
- return False, "Embed timeout (-t) must be an integer.", consumed
162
- if num < 0 or num > 600:
163
- return False, "Embed timeout (-t) must be between 0 and 600 seconds.", consumed
164
- return True, None, consumed
165
-
166
-
167
- def simulate_command(command: str) -> tuple[str | None, str | None, str | None]:
168
- """Very small shim to preview common commands."""
169
- text = command.strip()
170
- if not text:
171
- return None, None, None
172
- head, *rest = text.split(maxsplit=1)
173
- payload = rest[0] if rest else ""
174
- lowered = head.lower()
175
- if lowered == "echo":
176
- return payload, "echo", None
177
- if lowered == "embed":
178
- valid, error = validate_embed_payload(payload)
179
- return payload, "embed", error
180
- return None, head, None