Bug in extracting method text from .java files

I need to extract method implementation from java projects. I found a code on the javalang github issues https://github.com/c2nes/javalang/issues/49 but it fails sometimes. Can anyone take a look and see whats wrong?

On a colab notebook, clone the repo with

!git clone https://github.com/google/closure-compiler

Install javalang

!pip install javalang

Run the following code (it fails on other files too, not on every function but some)

import os
import re
import javalang
import json

def get_method_start_end(tree, method_node):
    startpos = None
    endpos = None
    startline = None
    endline = None
    for path, node in tree:
        if startpos is not None and method_node not in path:
            endpos = node.position
            endline = node.position.line if node.position is not None else None
            break
        if startpos is None and node == method_node:
            startpos = node.position
            startline = node.position.line if node.position is not None else None
    return startpos, endpos, startline, endline

def get_method_text(codelines, startpos, endpos, startline, endline, last_endline_index):
    if startpos is None:
        return "", None, None, None
    else:
        startline_index = startline - 1
        endline_index = endline - 1 if endpos is not None else None

        # 1. check for and fetch annotations
        if last_endline_index is not None:
            for line in codelines[(last_endline_index + 1):(startline_index)]:
                if "@" in line:
                    startline_index = startline_index - 1

        # 2. Add comments before method
        comments = []
        for line_index in range(startline_index - 1, -1, -1):
            line = codelines[line_index].strip()
            if line.startswith('//') or line.startswith('/*'):
                comments.insert(0, line)
            else:
                break

        method_lines = comments + codelines[startline_index:endline_index]
        method_text = 'n'.join(method_lines)
        method_text = method_text[:method_text.rfind("}") + 1]

        # 3. remove trailing rbrace for last methods & any external content/comments
        # if endpos is None and
        if not abs(method_text.count("}") - method_text.count("{")) == 0:
            # imbalanced braces
            brace_diff = abs(method_text.count("}") - method_text.count("{"))

            for _ in range(brace_diff):
                method_text = method_text[:method_text.rfind("}")]
                method_text = method_text[:method_text.rfind("}") + 1]

        last_endline_index = startline_index + len(method_lines) - 1

        return method_text, (startline_index + 1), (last_endline_index + 1), last_endline_index

def get_methods_info(java_content, file_path):
    code_lines = java_content.split('n')
    lex = None
    try:
        tree = javalang.parse.parse(java_content)
    except:
        print(f'Parsing failed for file: {file_path}')
        return None
    for _, method_node in tree.filter(javalang.tree.MethodDeclaration):

        startpos, endpos, startline, endline = get_method_start_end(tree, method_node)
        if endpos == None:
            raise ValueError(f"Check file: {file_path}, {method_node.name}")
            continue
        method_text, startline, endline, lex = get_method_text(code_lines, startpos, endpos, startline, endline, lex)
    return method_text

filename = "./closure-compiler/test/com/google/javascript/jscomp/Es6RewriteBlockScopedFunctionDeclarationTest.java"

with open(filename, 'r') as f:
    java_content = f.read()
    java_content = java_content.replace("@Nullable", "")
    java_content = java_content.replace(r"\$", "")

    java_content = re.sub(r'[^a-zA-Z](.+?)::new', lambda match: match.group(1).lower().removesuffix('[]'), java_content)

    methods_info = get_methods_info(java_content, filename)

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật