ollie/tools/lsp_definition

44 lines
1.4 KiB
Python
Executable File

#!/usr/bin/env python3
# ollie:parallel read
# args_json: {"type":"object","required":["path","line","col"],"properties":{"path":{"type":"string","description":"Absolute file path"},"line":{"type":"string","description":"Line number (1-indexed)"},"col":{"type":"string","description":"Column number (1-indexed)"}}}
# ollie:prompt
# ## lsp_definition
#
# Go to definition of symbol at position.
#
# **Args**: `[path, line, col]`
#
# ```
# lsp_definition(path="/abs/path.go", line="42", col="10")
# ```
#
# **Returns**: `file:line:col` location(s).
# ollie:end
import os
import sys
sys.path.insert(0, os.environ.get('OLLIE_TOOLS_PATH', os.path.dirname(os.path.abspath(__file__))))
from _lib.args import parse_args
from _lib.lsp.client import request
args = parse_args()
filepath = os.path.abspath(args.require("path"))
line = int(args.require("line")) - 1
col = int(args.require("col")) - 1
result = request("definition", file=filepath, line=line, col=col)
if not result:
print("(no definition found)")
sys.exit(0)
locations = result if isinstance(result, list) else [result]
for loc in locations:
uri = loc.get("uri", loc.get("targetUri", ""))
path = uri[7:] if uri.startswith("file://") else uri
pos = loc.get("range", loc.get("targetRange", {})).get("start", {})
ln = pos.get("line", 0) + 1
ch = pos.get("character", 0) + 1
print(f"{path}:{ln}:{ch}")