Skip to content

your regex logic in snippet() is brittle: #325

@shashanknr172-beep

Description

@shashanknr172-beep

Hi there your regex logic in snippet() looks like more brittle:

p= re.compile("^#+")
m= p.search(section_name)

some thing like these it is used

*you're treating section_name(a string passed by the user , like "## section") as if it's markdown content.
but in reality , we want to find the section header inside the file , not check the input string format , also headers and spacing , which often fails.

The change that can be done 👍

    1. Accept just the plain title text(e.g " Introduction") instead of forcing "## Introduction" .
    2. Build the regex dynamically to match headings in the file.

for example

@env.macro
def snippet(file_path, section_name, num_sections=1):
root = env.variables['config']['docs_dir']
full_path = os.path.join(root, file_path)

with open(full_path, 'r') as myfile:
    content = myfile.read()

# Match a heading that contains the given text
heading_pattern = re.compile(r'^(#+)\s+' + re.escape(section_name) + r'\s*$', re.MULTILINE)
start = heading_pattern.search(content)

if not start:
    return f"Section '{section_name}' not found in {file_path}"

section_level = len(start.group(1))  # number of '#' determines level
start_index = start.end()

# Find the next heading of same or higher level
next_heading_pattern = re.compile(r'^(#{1,' + str(section_level) + r'})\s+', re.MULTILINE)
following = [m for m in next_heading_pattern.finditer(content[start_index:])]

if len(following) == 0 or (num_sections - 1) >= len(following):
    result = content[start.start():]
else:
    end = following[num_sections - 1]
    result = content[start.start(): start_index + end.start()]

return result
  • These change can make the macro more robust and user-friendly.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions