PyAr / wiki

Los contenidos de la wiki de pyar
http://python.org.ar/wiki/
10 stars 39 forks source link

Issue 48 doble header #89

Closed tzulberti closed 4 years ago

tzulberti commented 4 years ago

Close #48

Al final lo que termine haciendo fue un script para poner el .. title: en cada una de las paginas. Las que tenian algun titulo, me basaba en el mismo. Las que no, se lo ponia en funcion del nombre

El script no lo subo al repo porque es un one time only, pero por si alguien le interesa, este es el script que use:

"""
Agrega los headers de todas las paginas
"""

import os

WIKI_PATH = os.path.dirname(__file__)
FILES_BASE_PATH = os.path.join(WIKI_PATH, 'pages')

LIST_OF_HEADERS_CHARS = [
    "=", '.', '-', ':',
]

def check_files(base_path, should_go_recursive=True):
    files, folders = scan_folder(base_path)
    for filename in files:
        original_content = open(filename).readlines()
        page_title, starting_index = get_page_title(filename, original_content)
        final_content = [
            '.. title: %s\n\n' % page_title.strip()
        ] + original_content[starting_index:]
        open(filename, 'w').writelines(final_content)

    if should_go_recursive:
        for folder in folders:
            check_files(folder)

def scan_folder(current_path):
    folders_to_scan = []
    current_files = []
    for filename in os.listdir(current_path):
        complete_path = os.path.join(current_path, filename)
        if os.path.isdir(complete_path):
            folders_to_scan.append(complete_path)
        else:
            current_files.append(complete_path)

    return (current_files, folders_to_scan)

def get_page_title(filename, content):
    file_title = os.path.basename(filename).replace("-", " ").replace(".rst", "").title()
    if len(content) < 2:
        return (file_title, 0)

    # busco la primer linea que tenga algo de contenido
    starting_index = 0
    for line in content:
        if line.strip():
            break
        else:
            starting_index += 1
    else:
        # el archivo esta vacio, y solo tiene lineas en blanco
        return (file_title, 0)

    if is_header_separator(content[starting_index]) and is_header_separator(content[starting_index + 2]):
        # =======
        # a title
        # =======
        return (content[starting_index + 1], starting_index + 3)
    elif is_header_separator(content[starting_index + 1]):
        # a title
        # =======
        return (content[starting_index], starting_index + 2)
    else:
        # just some content
        return (file_title, starting_index)

def is_header_separator(line):
    unique_chars = set(line.strip())
    if len(unique_chars) != 1:
        return False

    return unique_chars.intersection(LIST_OF_HEADERS_CHARS)

check_files(FILES_BASE_PATH)