← Files Power BI Report CopilotARCHIVED FILE

scripts/rdl_lint.py

4.54 KB · Nov 20, 2026 · 06:46 UTC

↓ Download file

See the change to this file →

#!/usr/bin/env python3
"""Bounded static checks for Microsoft RDL XML.
No query execution, no expressions, no live Power BI validation. Outputs JSON.
"""
from __future__ import annotations
import json, re, sys
from decimal import Decimal, InvalidOperation
from pathlib import Path
import xml.etree.ElementTree as ET

MAX_BYTES=2_000_000
CONVERSIONS={'in':Decimal('1'),'cm':Decimal('1')/Decimal('2.54'),'mm':Decimal('1')/Decimal('25.4'),
             'pt':Decimal('1')/Decimal('72'),'pc':Decimal('1')/Decimal('6')}
MEASURE=re.compile(r'^\s*(\d+(?:\.\d+)?)\s*(in|cm|mm|pt|pc)\s*$',re.I)
PARAM_REF=re.compile(r'Parameters!([A-Za-z_][\w]*)\.Value|Parameters\s*\(\s*["\']([^"\']+)["\']\s*\)',re.I)

def inch(text: str | None) -> Decimal | None:
    if not text: return None
    m=MEASURE.fullmatch(text)
    return Decimal(m.group(1))*CONVERSIONS[m.group(2).lower()] if m else None

def local(tag):return tag.rsplit('}',1)[-1]

def child(parent,name):
    if parent is None:return None
    return next((x for x in parent if local(x.tag)==name),None)

def children(parent,name):
    return [x for x in parent if local(x.tag)==name] if parent is not None else []

def text(parent,name):
    el=child(parent,name)
    return el.text.strip() if el is not None and el.text else None

def inspect_rdl(xml: bytes) -> dict:
    if len(xml)>MAX_BYTES:raise ValueError('RDL exceeds static inspection byte limit')
    if re.search(br'<!\s*(?:DOCTYPE|ENTITY)\b',xml,re.I):
        raise ValueError('DOCTYPE/ENTITY declarations are not accepted')
    try:root=ET.fromstring(xml)
    except ET.ParseError as ex:raise ValueError('Invalid RDL XML') from ex
    if local(root.tag)!='Report':raise ValueError('Expected an RDL Report root')
    findings=[]
    sections=child(root,'ReportSections')
    pages=[]
    if sections is not None:
        for sec in children(sections,'ReportSection'):
            pages.append((child(sec,'Page'),child(sec,'Body')))
    else:pages.append((child(root,'Page'),child(root,'Body')))
    for idx,(page,body) in enumerate(pages,1):
        if page is None or body is None:
            findings.append({'severity':'info','code':'PAGE_NOT_INSPECTABLE','section':idx,'message':'Page/body geometry not declared at expected location'})
            continue
        body_width=inch(text(body,'Width'))
        page_width=inch(text(page,'PageWidth'))
        l=inch(text(page,'LeftMargin')) or Decimal(0)
        r=inch(text(page,'RightMargin')) or Decimal(0)
        if body_width is not None and page_width is not None:
            total=body_width+l+r
            if total>page_width:
                findings.append({'severity':'warning','code':'PAGE_WIDTH_OVERFLOW','section':idx,
                                 'message':'Body width plus horizontal margins exceeds page width',
                                 'body_with_margins_in':str(total),'page_width_in':str(page_width)})
    params=child(root,'ReportParameters')
    declared=set()
    for p in children(params,'ReportParameter'):
        name=p.attrib.get('Name')
        if name: declared.add(name)
    datasets=child(root,'DataSets')
    inspected_query_params=0
    for ds in children(datasets,'DataSet'):
        q=child(ds,'Query')
        qp=child(q,'QueryParameters')
        for p in children(qp,'QueryParameter'):
            inspected_query_params+=1
            val=text(p,'Value') or ''
            for m in PARAM_REF.finditer(val):
                refer=m.group(1) or m.group(2)
                if refer not in declared:
                    findings.append({'severity':'warning','code':'UNKNOWN_REPORT_PARAMETER',
                                     'dataset':ds.attrib.get('Name'),
                                     'query_parameter':p.attrib.get('Name'),
                                     'referenced_parameter':refer,
                                     'message':'Dataset query expression references an undeclared report parameter'})
    return {'status':'STATIC_ONLY','section_count':len(pages),'report_parameters':sorted(declared),
            'query_parameters_inspected':inspected_query_params,'findings':findings,
            'disclaimer':'No queries, VB expressions, reports or exports were executed.'}

def main(argv=None):
    argv=list(sys.argv[1:] if argv is None else argv)
    if len(argv)!=1:
        print('Usage: rdl_lint.py path/to/report.rdl',file=sys.stderr);return 2
    try:
        out=inspect_rdl(Path(argv[0]).read_bytes())
    except (OSError,ValueError) as ex:
        print(json.dumps({'status':'ERROR','message':str(ex)}));return 1
    print(json.dumps(out,indent=2));return 0
if __name__=='__main__':raise SystemExit(main())

SHA-256: 2c1a4f0527c38cd6a3ef3de5071a412fac032d9b46ba8bb9fe588b58fc1f055d