Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
emscripten-core
GitHub Repository: emscripten-core/emscripten
Path: blob/main/site/source/get_wiki.py
4150 views
1
#!/usr/bin/env python3
2
# Copyright 2014 The Emscripten Authors. All rights reserved.
3
# Emscripten is available under two separate licenses, the MIT license and the
4
# University of Illinois/NCSA Open Source License. Both these licenses can be
5
# found in the LICENSE file.
6
7
#
8
# This script gets the Emscripten wiki, converts files from markdown to
9
# restructure text using pandoc (and also prepends the text with a title/heading
10
# based on the filename)
11
#
12
# It also fixes up inline code items to become links to api-reference
13
#
14
# It should be called prior to building the site.
15
#
16
17
import optparse
18
import os
19
import re
20
import shutil
21
import stat
22
import sys
23
import time
24
from pathlib import Path
25
26
import api_items
27
28
wiki_repo = 'https://github.com/emscripten-core/emscripten.wiki.git'
29
output_dir = './wiki_static/'
30
logfilename = 'log-get-wiki.txt'
31
32
# GetmMap of code items from api_items.py
33
mapped_wiki_inline_code = api_items.get_mapped_items()
34
# Add any additional mapped items that seem reasonable.
35
mapped_wiki_inline_code['getValue(ptr, type)'] = ':js:func:`getValue(ptr, type) <getValue>`'
36
mapped_wiki_inline_code['setValue(ptr, value, type)'] = ':js:func:`setValue(ptr, value, type) <setValue>`'
37
38
wiki_checkout = 'emscripten.wiki/'
39
temp_set_of_codemarkup = set()
40
logfile = open(logfilename, 'w')
41
# snapshot_version_information = '.. note:: This is a **snapshot** of the wiki: %s\n\n' % strftime("%a, %d %b %Y %H:%M", gmtime())
42
snapshot_version_information = '.. note:: This article was migrated from the wiki (%s) and is now the "master copy" (the version in the wiki will be deleted). It may not be a perfect rendering of the original but we hope to fix that soon!\n\n' % time.strftime("%a, %d %b %Y %H:%M", time.gmtime())
43
44
45
def CleanWiki():
46
"""Delete the wiki clone directory and all contained files.
47
"""
48
49
def errorhandler(func, path, exc_info):
50
# where func is os.listdir, os.remove, or os.rmdir; path is the argument to that function that caused it to fail; and exc_info is a tuple returned by sys.exc_info()
51
print(func)
52
print(path)
53
print(exc_info)
54
os.chmod(path, stat.S_IWRITE)
55
os.remove(path)
56
57
try:
58
shutil.rmtree(output_dir, ignore_errors=False, onerror=errorhandler)
59
print('Old wiki clone removed')
60
except OSError:
61
print('No directory to clean found')
62
63
64
def CloneWiki():
65
"""
66
Clone the wiki into a temporary location (first cleaning)
67
"""
68
# Clean up existing repo
69
CleanWiki()
70
71
# Create directory for output and temporary files
72
try:
73
os.makedirs(output_dir)
74
print('Created directory')
75
except OSError:
76
pass
77
78
# Clone
79
git_clone_command = 'git clone %s %s' % (wiki_repo, wiki_checkout)
80
print(git_clone_command)
81
os.system(git_clone_command)
82
83
84
def ConvertFilesToRst():
85
"""
86
Add template to specified page object (wikitools)
87
"""
88
indexfiletext = '============================\nWiki snapshot (ready-for-review)\n============================\n\n%s\n.. toctree::\n :maxdepth: 2\n' % snapshot_version_information
89
for file in os.listdir(wiki_checkout):
90
if not file.endswith(".md"):
91
continue
92
93
inputfilename = wiki_checkout + file
94
markdown = Path(inputfilename).read_text()
95
if 'This article has moved from the wiki to the new site' in markdown:
96
continue
97
if 'This page has been migrated to the main site' in markdown:
98
continue
99
100
print(file)
101
# get name of file
102
filenamestripped = os.path.splitext(file)[0]
103
indexfiletext += '\n %s' % filenamestripped
104
outputfilename = output_dir + filenamestripped + '.rst'
105
106
command = 'pandoc -f markdown -t rst -o "%s" "%s"' % (outputfilename, inputfilename)
107
print(command)
108
if os.system(command):
109
sys.exit(1)
110
title = filenamestripped.replace('-', ' ')
111
# print title
112
logfile.write('title from filename: %s \n' % title)
113
# add import message to title
114
title += ' (wiki-import)'
115
length = len(title)
116
# print length
117
headerbar = ''
118
for _ in range(length):
119
headerbar += '='
120
page_reference = filenamestripped
121
page_reference_link_text = '.. _%s:\n\n' % page_reference
122
titlebar = page_reference_link_text + headerbar + '\n' + title + '\n' + headerbar + '\n'
123
textinfile = ''
124
# Add titlebar to start of the file (from the filename)
125
textinfile += titlebar
126
# Add wiki snapshot information
127
128
textinfile += snapshot_version_information
129
130
with open(outputfilename) as infile:
131
for line in infile:
132
textinfile += line
133
134
# print textinfile
135
with open(outputfilename, 'w') as outfile:
136
outfile.write(textinfile)
137
138
# write the index
139
with open(output_dir + 'index.rst', 'w') as outfile:
140
outfile.write(indexfiletext)
141
142
143
def FixupConvertedRstFiles():
144
"""Add template to specified page object (wikitools)
145
"""
146
147
def fixInternalWikiLinks(aOldText):
148
"""
149
Fixes wiki links in [[linkname]] format by changing this to a document link in current directory.
150
"""
151
def fixwikilinks(matchobj):
152
# print 'matcobj0: %s' % matchobj.group(0)
153
# print 'matcobj1: %s' % matchobj.group(1)
154
linktext = matchobj.group(1)
155
linktext = linktext.replace(' ', '-')
156
# linktext = ':doc:`%s`' % linktext
157
# use reference for linking as allows pages to be moved around
158
linktext = ':ref:`%s`' % linktext
159
# print 'linkdoc: %s' % linktext
160
logfile.write('linkdoc: %s \n' % linktext)
161
return linktext
162
# print 'fixing wiki links'
163
return re.sub(r'\[\[(.+?)\]\]', fixwikilinks, aOldText)
164
165
def fixWikiCodeMarkupToCodeLinks(aOldText):
166
"""
167
Links "known" code objects if they are found in wiki markup.
168
"""
169
def fixcodemarkuplinks(matchobj):
170
# print 'Inline code: %s' % matchobj.group(0)
171
# print 'matcobj1: %s' % matchobj.group(1)
172
temp_set_of_codemarkup.add(matchobj.group(0))
173
linktext = matchobj.group(1)
174
if linktext in mapped_wiki_inline_code:
175
logfile.write('Replace: %s \n' % mapped_wiki_inline_code[linktext])
176
return mapped_wiki_inline_code[linktext]
177
178
return matchobj.group(0) # linktext
179
# print 'fixing up code markup to code reference'
180
return re.sub(r'``(.+?)``', fixcodemarkuplinks, aOldText)
181
182
for file in os.listdir(output_dir):
183
if file.endswith(".rst"):
184
input_file = output_dir + file
185
# print input_file
186
textinfile = ''
187
with open(input_file) as infile:
188
for line in infile:
189
textinfile += line
190
191
# print textinfile
192
# fix up broken wiki-page links in files
193
textinfile = fixInternalWikiLinks(textinfile)
194
195
# convert codemarkup to links if possible
196
textinfile = fixWikiCodeMarkupToCodeLinks(textinfile)
197
198
with open(input_file, 'w') as outfile:
199
outfile.write(textinfile)
200
201
logfile.write('\n\nCODE MARKUP THAT WONT BE LINKED (add entry to mapped_wiki_inline_code if one of these need to be linked. The tool get-api-items.py can be used to generate the list of the documented API items. \n')
202
for item in temp_set_of_codemarkup:
203
logfile.write('%s\n' % item)
204
205
206
# parser options
207
def main():
208
parser = optparse.OptionParser(version="%prog 0.1.1", usage="Usage: %prog [options] version")
209
parser.add_option("-c", "--clonewiki", action="store_true", default=False, dest="clonewiki", help="Clean and clone the latest wiki")
210
options, args = parser.parse_args()
211
212
print('Clone wiki: %s' % options.clonewiki)
213
if options.clonewiki:
214
CloneWiki()
215
# input = raw_input('CHECK ALL files were cloned! (look for "error: unable to create file" )\n')
216
217
ConvertFilesToRst()
218
FixupConvertedRstFiles()
219
print('See LOG for details: %s ' % logfilename)
220
221
222
if __name__ == '__main__':
223
sys.exit(main())
224
225