Skip to content

Add api_name to front matter if missing#1936

Open
lucafrance wants to merge 1 commit intoMicrosoftDocs:mainfrom
lucafrance:api_name
Open

Add api_name to front matter if missing#1936
lucafrance wants to merge 1 commit intoMicrosoftDocs:mainfrom
lucafrance:api_name

Conversation

@lucafrance
Copy link
Contributor

Script used:

import os
import re

folder_path = 'api'

def get_markdown_files(folder):
    """Get only markdown files in the main directory, not subdirectories, excluding those with '(enumerations)' or 'Word(textcolumns)' in the name."""
    return [
        os.path.join(folder, file)
        for file in os.listdir(folder)
        if file.endswith('.md')
        and os.path.isfile(os.path.join(folder, file))
        and "(enumerations)" not in file
        and "Word(textcolumns)" not in file
    ]

def has_front_matter(content):
    return re.search(r'^---', content, re.MULTILINE) is not None

def parse_front_matter(content):
    match = re.search(r'^(---.*?---)\n', content, re.MULTILINE | re.DOTALL)
    if match:
        return match.group(1).strip()
    return ''

def clean_api_name(filename):
    """Remove extension and any parenthesis content from filename."""
    name = os.path.splitext(filename)[0]
    name = re.sub(r"\s*\(.*?\)", "", name).strip()
    return name

def insert_api_name(front_matter, api_name):
    lines = front_matter.splitlines()
    new_lines = []
    inserted = False
    insert_index = None

    # Track last index of title, keywords, f1_keywords (including list items)
    for i, line in enumerate(lines):
        if line.strip().startswith("title:") or line.strip().startswith("keywords:") or line.strip().startswith("f1_keywords:"):
            insert_index = i
            if line.strip().startswith("keywords:") or line.strip().startswith("f1_keywords:"):
                j = i + 1
                while j < len(lines) and lines[j].strip().startswith("-"):
                    insert_index = j
                    j += 1

    if insert_index is not None:
        for i, line in enumerate(lines):
            new_lines.append(line)
            if i == insert_index and not inserted:
                new_lines.append(f"api_name:\n- {api_name}")
                inserted = True
    else:
        if lines[-1].strip() == "---":
            new_lines.insert(len(lines)-1, f"api_name:\n- {api_name}")
        else:
            new_lines.append(f"api_name:\n- {api_name}")

    return "\n".join(new_lines)

def update_front_matter_with_api_name(filepath, api_name):
    with open(filepath, 'r', encoding="utf-8") as file:
        content = file.read()

    front_matter = parse_front_matter(content)

    if 'api_name' not in front_matter:
        updated_front_matter = insert_api_name(front_matter, api_name)
        new_content = re.sub(
            r'^(---.*?---)\n',
            f"{updated_front_matter}\n",
            content,
            flags=re.MULTILINE | re.DOTALL
        )
        with open(filepath, 'w', encoding="utf-8") as file:
            file.write(new_content)

def main():
    markdown_files = get_markdown_files(folder_path)
    for filepath in markdown_files:
        filename = os.path.basename(filepath)
        api_name = clean_api_name(filename)

        with open(filepath, 'r', encoding="utf-8") as file:
            content = file.read()

        if has_front_matter(content):
            front_matter = parse_front_matter(content)
            if 'api_name' not in front_matter.lower():
                update_front_matter_with_api_name(filepath, api_name)
                print(f"Updated '{filepath}': added 'api_name: [{api_name}]'")
            else:
                print(f"'{filepath}' already has 'api_name'")

if __name__ == "__main__":
    main()

Script used:

```python
import os
import re

folder_path = 'api'

def get_markdown_files(folder):
    """Get only markdown files in the main directory, not subdirectories, excluding those with '(enumerations)' or 'Word(textcolumns)' in the name."""
    return [
        os.path.join(folder, file)
        for file in os.listdir(folder)
        if file.endswith('.md')
        and os.path.isfile(os.path.join(folder, file))
        and "(enumerations)" not in file
        and "Word(textcolumns)" not in file
    ]

def has_front_matter(content):
    return re.search(r'^---', content, re.MULTILINE) is not None

def parse_front_matter(content):
    match = re.search(r'^(---.*?---)\n', content, re.MULTILINE | re.DOTALL)
    if match:
        return match.group(1).strip()
    return ''

def clean_api_name(filename):
    """Remove extension and any parenthesis content from filename."""
    name = os.path.splitext(filename)[0]
    name = re.sub(r"\s*\(.*?\)", "", name).strip()
    return name

def insert_api_name(front_matter, api_name):
    lines = front_matter.splitlines()
    new_lines = []
    inserted = False
    insert_index = None

    # Track last index of title, keywords, f1_keywords (including list items)
    for i, line in enumerate(lines):
        if line.strip().startswith("title:") or line.strip().startswith("keywords:") or line.strip().startswith("f1_keywords:"):
            insert_index = i
            if line.strip().startswith("keywords:") or line.strip().startswith("f1_keywords:"):
                j = i + 1
                while j < len(lines) and lines[j].strip().startswith("-"):
                    insert_index = j
                    j += 1

    if insert_index is not None:
        for i, line in enumerate(lines):
            new_lines.append(line)
            if i == insert_index and not inserted:
                new_lines.append(f"api_name:\n- {api_name}")
                inserted = True
    else:
        if lines[-1].strip() == "---":
            new_lines.insert(len(lines)-1, f"api_name:\n- {api_name}")
        else:
            new_lines.append(f"api_name:\n- {api_name}")

    return "\n".join(new_lines)

def update_front_matter_with_api_name(filepath, api_name):
    with open(filepath, 'r', encoding="utf-8") as file:
        content = file.read()

    front_matter = parse_front_matter(content)

    if 'api_name' not in front_matter:
        updated_front_matter = insert_api_name(front_matter, api_name)
        new_content = re.sub(
            r'^(---.*?---)\n',
            f"{updated_front_matter}\n",
            content,
            flags=re.MULTILINE | re.DOTALL
        )
        with open(filepath, 'w', encoding="utf-8") as file:
            file.write(new_content)

def main():
    markdown_files = get_markdown_files(folder_path)
    for filepath in markdown_files:
        filename = os.path.basename(filepath)
        api_name = clean_api_name(filename)

        with open(filepath, 'r', encoding="utf-8") as file:
            content = file.read()

        if has_front_matter(content):
            front_matter = parse_front_matter(content)
            if 'api_name' not in front_matter.lower():
                update_front_matter_with_api_name(filepath, api_name)
                print(f"Updated '{filepath}': added 'api_name: [{api_name}]'")
            else:
                print(f"'{filepath}' already has 'api_name'")

if __name__ == "__main__":
    main()
```
@learn-build-service-prod
Copy link
Contributor

PoliCheck Scan Report

The following report lists PoliCheck issues in PR files. Before you merge the PR, you must fix all severity-1 and severity-2 issues. The AI Review Details column lists suggestions for either removing or replacing the terms. If you find a false positive result, mention it in a PR comment and include this text: #policheck-false-positive. This feedback helps reduce false positives in future scans.

✅ No issues found

More information about PoliCheck

Information: PoliCheck | Severity Guidance | Term
For any questions: Try searching the learn.microsoft.com contributor guides or post your question in the Learn support channel.

@learn-build-service-prod
Copy link
Contributor

Learn Build status updates of commit a5dffce:

✅ Validation status: passed

File Status Preview URL Details
api/Access.allmacros.md ✅Succeeded View
api/Access.application.davg.md ✅Succeeded View
api/Access.application.returnvars.md ✅Succeeded View
api/Access.CodeProject.IsSQLBackend.md ✅Succeeded View
api/Access.commandbutton.quickstylemask.md ✅Succeeded View
api/Access.form.recordsettype.md ✅Succeeded View
api/Access.format.propertydate.time.md ✅Succeeded View
api/Access.format.propertynumber.and.currency.md ✅Succeeded View
api/Access.format.propertytext.and.memo.md ✅Succeeded View
api/Access.format.propertyyes.no.md ✅Succeeded View
api/Access.md ✅Succeeded View
api/Access.navigationbutton.quickstylemask.md ✅Succeeded View
api/Access.oldconstants.md ✅Succeeded View
api/Access.report.shape.md ✅Succeeded View
api/Access.RowSourceType.md ✅Succeeded View
api/Access.togglebutton.quickstylemask.md ✅Succeeded View
api/Excel.application.chartdatapointtrack.md ✅Succeeded View
api/Excel.application.enablecheckfileextensions.md ✅Succeeded View
api/Excel.application.enablemacroanimations.md ✅Succeeded View
api/Excel.application.flashfill.md ✅Succeeded View
api/Excel.application.flashfillmode.md ✅Succeeded View
api/Excel.application.mergeinstances.md ✅Succeeded View
api/Excel.application.quickanalysis.md ✅Succeeded View
api/Excel.application.sheetbeforedelete.md ✅Succeeded View
api/Excel.application.sheetlensgalleryrendercomplete.md ✅Succeeded View

This comment lists only the first 25 files in the pull request.
For more details, please refer to the build report.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

Comments