~cypheon/ocaml-docset

ocaml-docset/mkindex.py -rwxr-xr-x 6.1 KiB
299351cf — Johann Rudloff Add pointer to better maintained version 3 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
#!/usr/bin/env python3

import os
import re
import sqlite3
import urllib.parse

from bs4 import BeautifulSoup

TYPE_CONSTRUCTOR = 'Constructor'
TYPE_EXCEPTION   = 'Exception'
TYPE_FIELD       = 'Field'
TYPE_FUNCTION    = 'Function'
TYPE_LIBRARY     = 'Library'
TYPE_MODULE      = 'Module'
TYPE_TYPE        = 'Type'
TYPE_VALUE       = 'Value'

RE_LIBRARY_CHAPTER = re.compile(r'.+The ([^ ]+) library(?:|: .+)')

def add_index(name, typ, path):
    c = conn.cursor()
    c.execute('''INSERT OR IGNORE INTO searchIndex(name, type, path) VALUES (?, ?, ?)''',
              (name, typ, path))
    conn.commit()
    # print(f'{name:32s}  {typ:12s}  {path}')

def contains(node, string):
    for s in node.strings:
        if string in s:
            return True
    return False

def run(filename, file_path):
    with open(file_path) as fp:
        soup = BeautifulSoup(fp, 'html.parser')
    soup.made_changes = False
    h1 = soup.find('h1')
    if h1 is None:
        if not os.path.basename(filename).startswith('type_'):
            print('WARN: no h1: ' + filename)
        return soup, []
    h1_content = list(h1.stripped_strings)
    libmatch = RE_LIBRARY_CHAPTER.fullmatch(' '.join(h1_content))
    def anchor(id):
        return filename + '#' + id

    if h1_content[0].startswith('Module') or h1_content[0].startswith('Functor'):
        module_name = h1_content[1]
        add_index(module_name, TYPE_MODULE, filename)
        handle_module(filename, module_name, soup)
        return soup, []
    elif libmatch is not None:
        libname = libmatch.group(1)
        add_index(libname, TYPE_LIBRARY, anchor(h1['id']))
        handle_library(filename, libname, soup)
        return soup, []
    else:
        if not os.path.basename(filename).startswith('index_'):
            print('WARN: no module: ' + filename)
        return soup, []

def anchor_element(soup, typ, id):
    id_quoted = urllib.parse.quote(id, safe='')
    a = soup.new_tag('a')
    a.attrs['name'] = f'//apple_ref/cpp/{typ}/{id_quoted}'
    a.attrs['class'] = 'dashAnchor'
    soup.made_changes = True
    return a

RE_LIB_TYPE = re.compile(r'type (?:.+ |)([a-zA-Z_][a-zA-Z0-9_]*)')
RE_LIB_EXN = re.compile(r'exception ([a-zA-Z_][a-zA-Z0-9_]*)(?: of .+|)')

def handle_library(filename, library_name, soup):
    def anchor(id):
        return filename + '#' + id

    next_id = {'id': 0}
    def autoid():
        id, next_id['id'] = next_id['id'], next_id['id'] + 1
        return f'autoid_{id:04x}'
    def getid(element):
        if 'id' not in element.attrs:
            element['id'] = autoid()
            soup.made_changes = True
        return element['id']

    for pre in soup.find_all('pre'):
        pretext = ' '.join(pre.stripped_strings)
        m_type = RE_LIB_TYPE.fullmatch(pretext)
        if m_type is not None:
            typname = m_type.group(1)
            add_index(typname, TYPE_TYPE, anchor(getid(pre)))
            pre.insert_before(anchor_element(soup, TYPE_TYPE, typname))
            continue

        m_exn = RE_LIB_EXN.fullmatch(pretext)
        if m_exn is not None:
            exnname = m_exn.group(1)
            add_index(exnname, TYPE_EXCEPTION, anchor(getid(pre)))
            pre.insert_before(anchor_element(soup, TYPE_EXCEPTION, exnname))
            continue

def handle_module(filename, module_name, soup):
    def anchor(id):
        return filename + '#' + id

    for span in soup.find_all('span', id=True):
        spanid = span['id']
        if spanid.startswith('TYPEELT'):
            name = spanid[7:]
            # this can either be a constructor or a record field
            # full_code = ' '.join(span.parent.stripped_strings)
            if name.split('.')[-1][0].islower():
                typ = TYPE_FIELD
            else:
                typ = TYPE_CONSTRUCTOR
            add_index(f'{module_name}.{name}', typ, anchor(spanid))
            span.parent.insert_before(anchor_element(soup, typ, name))

        elif spanid.startswith('TYPE'):
            name = spanid[4:]
            span.parent.insert_before(anchor_element(soup, TYPE_TYPE, name))
            add_index(f'{module_name}.{name}', TYPE_TYPE, anchor(spanid))
            # add_index(f'{module_name}.{name}', TYPE_TYPE, anchor(f'//apple_ref/cpp/{TYPE_TYPE}/{name}'))
        elif spanid.startswith('EXCEPTION'):
            name = spanid[9:]
            add_index(f'{module_name}.{name}', TYPE_EXCEPTION, anchor(spanid))
            span.parent.insert_before(anchor_element(soup, TYPE_EXCEPTION, name))
        elif spanid.startswith('VAL'):
            name = spanid[3:]
            if contains(span.parent, '->'):
                valtype = TYPE_FUNCTION
            else:
                valtype = TYPE_VALUE
            add_index(f'{module_name}.{name}', valtype, anchor(spanid))
            span.parent.insert_before(anchor_element(soup, valtype, name))
            # print(list(span.parent.strings))

if __name__ == '__main__':
    import glob
    import shutil
    import sys
    import traceback

    input_dir = sys.argv[1]
    output_dir = sys.argv[2]
    files = glob.glob(input_dir + '/**/*.html', recursive=True)

    db_filename = os.path.join(output_dir, 'docSet.dsidx')

    if os.path.isfile(db_filename):
        os.unlink(db_filename)
    conn = sqlite3.connect(db_filename)
    c = conn.cursor()
    c.execute('''CREATE TABLE searchIndex(id INTEGER PRIMARY KEY, name TEXT, type TEXT, path TEXT)''')
    c.execute('''CREATE UNIQUE INDEX anchor ON searchIndex (name, type, path)''')
    conn.commit()

    for filename in files:
        relname = os.path.relpath(filename, start=input_dir)
        try:
            output_filename = os.path.join(output_dir, 'Documents', relname)
            if not os.path.isdir(os.path.dirname(output_filename)):
                os.makedirs(os.path.dirname(output_filename))
            doc, entries = run(relname, filename)
            if doc is not None and doc.made_changes:
                with open(output_filename, 'w') as f:
                    f.write(str(doc))
            else:
                # No need to copy, this has already been taken care of by make
                # shutil.copy(filename, output_filename)
                pass
        except:
            traceback.print_exc()