|
| 1 | +import os |
| 2 | +import sys |
| 3 | + |
| 4 | +import grpc |
| 5 | + |
| 6 | +# The following two insertions fix the broken pb import paths |
| 7 | +sys.path.insert(0, os.path.join(os.path.dirname(__file__), |
| 8 | + "github/com/bblfsh/sdk/protocol")) |
| 9 | +sys.path.insert(0, os.path.dirname(__file__)) |
| 10 | +from bblfsh.github.com.bblfsh.sdk.protocol.generated_pb2 import ParseUASTRequest |
| 11 | +from bblfsh.github.com.bblfsh.sdk.protocol.generated_pb2_grpc import ProtocolServiceStub |
| 12 | + |
| 13 | + |
| 14 | +class BblfshClient(object): |
| 15 | + """ |
| 16 | + Babelfish gRPC client. Currently it is only capable of fetching UASTs. |
| 17 | + """ |
| 18 | + |
| 19 | + def __init__(self, endpoint): |
| 20 | + """ |
| 21 | + Initializes a new instance of BblfshClient. |
| 22 | +
|
| 23 | + :param endpoint: The address of the Babelfish server, \ |
| 24 | + for example "0.0.0.0:9432" |
| 25 | + :type endpoint: str |
| 26 | + """ |
| 27 | + self._channel = grpc.insecure_channel(endpoint) |
| 28 | + self._stub = ProtocolServiceStub(self._channel) |
| 29 | + |
| 30 | + def parse_uast(self, filename, language=None, contents=None): |
| 31 | + """ |
| 32 | + Queries the Babelfish server and receives the UAST for the specified |
| 33 | + file. |
| 34 | +
|
| 35 | + :param filename: The path to the file. Can be arbitrary if contents \ |
| 36 | + is not None. |
| 37 | + :param language: The programming language of the file. Refer to \ |
| 38 | + https://doc.bblf.sh/languages.html for the list of \ |
| 39 | + currently supported languages. None means autodetect. |
| 40 | + :param contents: The contents of the file. IF None, it is read from \ |
| 41 | + filename. |
| 42 | + :type filename: str |
| 43 | + :type language: str |
| 44 | + :type contents: str |
| 45 | + :return: UAST object. |
| 46 | + """ |
| 47 | + if contents is None: |
| 48 | + with open(filename) as fin: |
| 49 | + contents = fin.read() |
| 50 | + request = ParseUASTRequest(filename=os.path.basename(filename), |
| 51 | + content=contents, |
| 52 | + language=self._scramble_language(language)) |
| 53 | + response = self._stub.ParseUAST(request) |
| 54 | + return response |
| 55 | + |
| 56 | + @staticmethod |
| 57 | + def _scramble_language(lang): |
| 58 | + if lang is None: |
| 59 | + return None |
| 60 | + lang = lang.lower() |
| 61 | + lang = lang.replace(" ", "-") |
| 62 | + lang = lang.replace("+", "p") |
| 63 | + lang = lang.replace("#", "sharp") |
| 64 | + return lang |
0 commit comments