-
Notifications
You must be signed in to change notification settings - Fork 1
/
sconstruct
266 lines (233 loc) · 10.3 KB
/
sconstruct
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# NVDA add-on template SCONSTRUCT file
#Copyright (C) 2018Paulber19 <[email protected]>
#This file is covered by the GNU General Public License.
#See the file COPYING.txt for more details.
import codecs
import gettext
import os
import os.path
import zipfile
import sys
py3 = sys.version.startswith("3")
import buildVars
if py3:
import txt2tags as txt2tags
else:
import txt2tags25 as txt2tags
import markdown2 as markdown
def getTranslatedAddonSummary(buildVars, localeLang):
try:
# No ugettext in Python 3.
if sys.version_info.major == 2:
_ = gettext.translation("nvda", localedir=os.path.join("addon", "locale"), languages=[localeLang]).ugettext
else:
_ = gettext.translation("nvda", localedir=os.path.join("addon", "locale"), languages=[localeLang]).gettext
summary = _(buildVars.addon_info["addon_summary"])
except:
summary = buildVars.addon_info["addon_summary"]
return summary
def writeHTMLFile(dest, htmlText, lang, title, cssFileName):
cssFile =cssFileName if cssFileName is not None else "style.css"
#lang = os.path.basename(os.path.dirname(dest)).replace('_', '-')
with codecs.open(dest, "w", "utf-8") as f:
f.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n" +
" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" +
"<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"%s\" lang=\"%s\">\n" % (lang, lang) +
"<head>\n" +
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>\n" +
"<link rel=\"stylesheet\" type=\"text/css\" href=\"../%s\" media=\"screen\"/>\n"%cssFile +
"<title>%s</title>\n" % title +
"</head>\n"
)
f.write(htmlText)
f.write("\n</html>\n")
f.close()
def getHTMLBody(dest):
src = codecs.open( dest, "r","utf_8",errors="replace")
startTag= "</head>"
endTag= "<!-- html code generated"
appendLine = False
text =[]
for sLine in src:
line = sLine.lower()
startTagFound = line.find(startTag)
endTagFound = line.find(endTag)
if startTagFound >= 0:
appendLine = True
sLine = sLine[startTagFound+len(startTag):]
text.append(sLine)
continue
elif endTagFound >=0:
sLine = sLine[: endTagFound]
text.append(sLine)
break
if appendLine:
text.append(sLine)
text.append("</body>")
return "".join(text)
def t2t2html(source, dest):
txt2tags.exec_command_line([source,])
htmlText = getHTMLBody(dest)
lang = os.path.basename(os.path.dirname(source)).replace('_', '-')
localeLang = os.path.basename(os.path.dirname(source))
summary = getTranslatedAddonSummary(buildVars, localeLang)
title=u"{0} {1}".format(summary, buildVars.addon_info["addon_version"])
writeHTMLFile(dest, htmlText, lang, title, cssFileName = "style_t2t.css")
def md2html(source, dest):
lang = os.path.basename(os.path.dirname(source)).replace('_', '-')
localeLang = os.path.basename(os.path.dirname(source))
summary = getTranslatedAddonSummary(buildVars, localeLang)
title=u"{0} {1}".format(summary, buildVars.addon_info["addon_version"])
headerDic = {
"[[!meta title=\"": "# ",
"\"]]": " #",
}
with codecs.open(source, "r", "utf-8") as f:
mdText = f.read()
if sys.version_info.major == 2:
for k, v in headerDic.iteritems():
mdText = mdText.replace(k, v, 1)
else:
for k, v in headerDic.items():
mdText = mdText.replace(k, v, 1)
htmlText = "<body>\n" +markdown.markdown(mdText) +"\n</body>"
writeHTMLFile(dest, htmlText, lang, title, cssFileName = "style.css")
def generateT2tHelpFiles (source, target, env, for_signature):
action = env.Action(lambda target, source, env : t2t2html(source[0].abspath, target[0].abspath) and None,
lambda target, source, env : "Generating %s" % target[0])
return action
def generateMDHelpFiles (source, target, env, for_signature):
action = env.Action(lambda target, source, env : md2html(source[0].abspath, target[0].abspath) and None,
lambda target, source, env : "Generating %s" % target[0])
return action
env = Environment(ENV=os.environ, tools=['gettexttool'])
env.Append(**buildVars.addon_info)
addonFile = env.File("${addon_name}-${addon_version}.nvda-addon")
def addonGenerator(target, source, env, for_signature):
action = env.Action(lambda target, source, env : createAddonBundleFromPath(source[0].abspath, target[0].abspath) and None,
lambda target, source, env : "Generating Addon %s" % target[0])
return action
def manifestGenerator(target, source, env, for_signature):
action = env.Action(lambda target, source, env : generateManifest(source[0].abspath, target[0].abspath) and None,
lambda target, source, env : "Generating manifest %s" % target[0])
return action
def translatedManifestGenerator(target, source, env, for_signature):
dir = os.path.abspath(os.path.join(os.path.dirname(str(source[0])), ".."))
lang = os.path.basename(dir)
action = env.Action(lambda target, source, env : generateTranslatedManifest(source[1].abspath, lang, target[0].abspath) and None,
lambda target, source, env : "Generating translated manifest %s" % target[0])
return action
env['BUILDERS']['NVDAAddon'] = Builder(generator=addonGenerator)
env['BUILDERS']['markdown']=Builder(generator = generateMDHelpFiles,
suffix='.html',
src_suffix='.md')
env['BUILDERS']['txt2tags']=Builder(generator = generateT2tHelpFiles,
suffix='.html',
src_suffix='.t2t')
env['BUILDERS']['NVDAManifest'] = Builder(generator=manifestGenerator)
env['BUILDERS']['NVDATranslatedManifest'] = Builder(generator=translatedManifestGenerator)
def createAddonHelp(dir):
docsDir = os.path.join(dir, "doc")
# copy (to update) readme.md file (if exists) from addon/doc/en folder to repository root
readmePath = os.path.join(docsDir, "en", "readme.md")
if os.path.isfile(readmePath):
#readmeTarget = env.Command(readmePath, "readme.md", Copy("$TARGET", "$SOURCE"))
readmeTarget = env.Command( "readme.md",readmePath, Copy("$TARGET", "$SOURCE"))
env.Depends(addon, readmeTarget)
env.NoClean(readmeTarget)
cssPath = os.path.join(docsDir, "style.css")
if os.path.isfile(cssPath):
cssTarget = env.Command( "style.css",cssPath, Copy("$TARGET", "$SOURCE"))
env.Depends(addon, cssTarget)
env.NoClean(cssTarget)
else:
# copy readme.md file (if exists) from repository root to addon/doc/en folder
if os.path.isfile("readme.md"):
readmeTarget = env.Command(readmePath, "readme.md", Copy("$TARGET", "$SOURCE"))
env.Depends(addon, readmeTarget)
# copy css file (if exists) from repository root to addon/doc folder
if os.path.isfile("style.css"):
cssPath = os.path.join(docsDir, "style.css")
cssTarget = env.Command(cssPath, "style.css", Copy("$TARGET", "$SOURCE"))
env.Depends(addon, cssTarget)
def createAddonBundleFromPath(path, dest):
""" Creates a bundle from a directory that contains an addon manifest file."""
basedir = os.path.abspath(path)
with zipfile.ZipFile(dest, 'w', zipfile.ZIP_DEFLATED) as z:
# FIXME: the include/exclude feature may or may not be useful. Also python files can be pre-compiled.
for dir, dirnames, filenames in os.walk(basedir):
relativePath = os.path.relpath(dir, basedir)
for filename in filenames:
pathInBundle = os.path.join(relativePath, filename)
absPath = os.path.join(dir, filename)
if pathInBundle not in buildVars.excludedFiles: z.write(absPath, pathInBundle)
return dest
def generateManifest(source, dest):
with codecs.open(source, "r", "utf-8") as f:
manifest_template = f.read()
manifest = manifest_template.format(**buildVars.addon_info)
with codecs.open(dest, "w", "utf-8") as f:
f.write(manifest)
def generateTranslatedManifest(source, language, out):
# No ugettext in Python 3.
if sys.version_info.major == 2:
_ = gettext.translation("nvda", localedir=os.path.join("addon", "locale"), languages=[language]).ugettext
else:
_ = gettext.translation("nvda", localedir=os.path.join("addon", "locale"), languages=[language]).gettext
vars = {}
for var in ("addon_summary", "addon_description"):
vars[var] = _(buildVars.addon_info[var])
with codecs.open(source, "r", "utf-8") as f:
manifest_template = f.read()
result = manifest_template.format(**vars)
with codecs.open(out, "w", "utf-8") as f:
f.write(result)
def expandGlobs(files):
return [f for pattern in files for f in env.Glob(pattern)]
addon = env.NVDAAddon(addonFile, env.Dir('addon'))
pythonFiles = expandGlobs(buildVars.pythonSources)
for file in pythonFiles:
env.Depends(addon, file)
# Pot target
i18nFiles = expandGlobs(buildVars.i18nSources)
gettextvars={
'gettext_package_bugs_address' : '[email protected]',
'gettext_package_name' : buildVars.addon_info['addon_name'],
'gettext_package_version' : buildVars.addon_info['addon_version']
}
pot = env.gettextPotFile("${addon_name}-${addon_version}.pot", i18nFiles, **gettextvars)
env.Alias('pot', pot)
env.Depends(pot, i18nFiles)
mergePot = env.gettextMergePotFile("${addon_name}-merge.pot", i18nFiles, **gettextvars)
env.Alias('mergePot', mergePot)
env.Depends(mergePot, i18nFiles)
# Generate Manifest path
manifest = env.NVDAManifest(os.path.join("addon", "manifest.ini"), os.path.join("manifest.ini.tpl"))
# Ensure manifest is rebuilt if buildVars is updated.
env.Depends(manifest, "buildVars.py")
env.Depends(addon, manifest)
createAddonHelp("addon") # We need at least doc in English and should enable the Help button for the add-on in Add-ons Manager
langDirs = [f for f in env.Glob(os.path.join("addon", "locale", "*"))]
#Allow all NVDA's gettext po files to be compiled in source/locale, and manifest files to be generated
for dir in langDirs:
poFile = dir.File(os.path.join("LC_MESSAGES", "nvda.po"))
if os.path.exists(str(poFile)):
moFile=env.gettextMoFile(poFile)
env.Depends(moFile, poFile)
translatedManifest = env.NVDATranslatedManifest(dir.File("manifest.ini"), [moFile, os.path.join("manifest-translated.ini.tpl")])
env.Depends(translatedManifest, ["buildVars.py"])
env.Depends(addon, [translatedManifest, moFile])
#Convert markdown files to html
for mdFile in env.Glob(os.path.join('addon', 'doc', '*', '*.md')):
mdhtmlFile = env.markdown(mdFile)
if os.path.exists(str(poFile)):
env.Depends(mdhtmlFile, [mdFile, moFile])
env.Depends(addon, mdhtmlFile)
#Convert txt2tags files to html
for t2tFile in env.Glob(os.path.join('addon', 'doc', '*', '*.t2t')):
t2thtmlFile = env.txt2tags(t2tFile)
if os.path.exists(str(poFile)):
env.Depends(t2thtmlFile, [t2tFile, moFile])
env.Depends(addon,t2thtmlFile)
env.Default(addon)