Skip to content

Commit 9b90144

Browse files
committed
Add build tooling
1 parent fd92c9e commit 9b90144

File tree

6 files changed

+333
-1
lines changed

6 files changed

+333
-1
lines changed

Diff for: .gitignore

+10-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,14 @@
1+
# ---> SourceMod
12
# Ignore compiled SourceMod plugins
3+
24
*.smx
35

4-
# Ignore build outputs
6+
# Ignore ninja build stuff
7+
# (These should be handled with configure.py)
8+
**/__pycache__
59
build/
10+
build.ninja
11+
12+
# Ignore personal configuration files copied from contrib
13+
/modd.conf
14+
/uploader.ini

Diff for: .gitmodules

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
[submodule "third_party/vendored/stocksoup"]
2+
path = third_party/vendored/stocksoup
3+
url = https://github.com/nosoop/stocksoup.git

Diff for: configure.py

+120
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
#!/usr/bin/python
2+
3+
# plugin names, relative to `scripting/`
4+
plugins = [
5+
'tf2utils.sp',
6+
]
7+
8+
# files to copy to builddir, relative to root
9+
# plugin names from previous list will be copied automatically
10+
copy_files = [
11+
'scripting/include/tf2utils.inc',
12+
'gamedata/tf2.utils.nosoop.txt',
13+
]
14+
15+
# additional directories for sourcepawn include lookup
16+
# `scripting/include` is explicitly included
17+
include_dirs = [
18+
'third_party/vendored'
19+
]
20+
21+
# required version of spcomp (presumably pinned to SM version)
22+
spcomp_min_version = (1, 10)
23+
24+
########################
25+
# build.ninja script generation below.
26+
27+
import contextlib
28+
import misc.ninja_syntax as ninja_syntax
29+
import misc.spcomp_util
30+
import os
31+
import sys
32+
import argparse
33+
import platform
34+
import shutil
35+
36+
parser = argparse.ArgumentParser('Configures the project.')
37+
parser.add_argument('--spcomp-dir',
38+
help = 'Directory with the SourcePawn compiler. Will check PATH if not specified.')
39+
40+
args = parser.parse_args()
41+
42+
print("""Checking for SourcePawn compiler...""")
43+
spcomp = shutil.which('spcomp', path = args.spcomp_dir)
44+
if 'x86_64' in platform.machine():
45+
# Use 64-bit spcomp if architecture supports it
46+
spcomp = shutil.which('spcomp64', path = args.spcomp_dir) or spcomp
47+
if not spcomp:
48+
raise FileNotFoundError('Could not find SourcePawn compiler.')
49+
50+
available_version = misc.spcomp_util.extract_version(spcomp)
51+
version_string = '.'.join(map(str, available_version))
52+
print('Found SourcePawn compiler version', version_string, 'at', os.path.abspath(spcomp))
53+
54+
if spcomp_min_version > available_version:
55+
raise ValueError("Failed to meet required compiler version "
56+
+ '.'.join(map(str, spcomp_min_version)))
57+
58+
with contextlib.closing(ninja_syntax.Writer(open('build.ninja', 'wt'))) as build:
59+
build.comment('This file is used to build SourceMod plugins with ninja.')
60+
build.comment('The file is automatically generated by configure.py')
61+
build.newline()
62+
63+
vars = {
64+
'configure_args': sys.argv[1:],
65+
'root': '.',
66+
'builddir': 'build',
67+
'spcomp': spcomp,
68+
'spcflags': [ '-i${root}/scripting/include', '-h', '-v0' ]
69+
}
70+
71+
vars['spcflags'] += ('-i{}'.format(d) for d in include_dirs)
72+
73+
for key, value in vars.items():
74+
build.variable(key, value)
75+
build.newline()
76+
77+
build.comment("""Regenerate build files if build script changes.""")
78+
build.rule('configure',
79+
command = sys.executable + ' ${root}/configure.py ${configure_args}',
80+
description = 'Reconfiguring build', generator = 1)
81+
82+
build.build('build.ninja', 'configure',
83+
implicit = [ '${root}/configure.py', '${root}/misc/ninja_syntax.py' ])
84+
build.newline()
85+
86+
build.rule('spcomp', deps = 'msvc',
87+
command = '${spcomp} ${in} ${spcflags} -o ${out}',
88+
description = 'Compiling ${out}')
89+
build.newline()
90+
91+
# Platform-specific copy instructions
92+
if platform.system() == "Windows":
93+
build.rule('copy', command = 'cmd /c copy ${in} ${out} > NUL',
94+
description = 'Copying ${out}')
95+
elif platform.system() == "Linux":
96+
build.rule('copy', command = 'cp ${in} ${out}', description = 'Copying ${out}')
97+
build.newline()
98+
99+
build.comment("""Compile plugins specified in `plugins` list""")
100+
for plugin in plugins:
101+
smx_plugin = os.path.splitext(plugin)[0] + '.smx'
102+
103+
sp_file = os.path.normpath(os.path.join('$root', 'scripting', plugin))
104+
105+
smx_file = os.path.normpath(os.path.join('$builddir', 'plugins', smx_plugin))
106+
build.build(smx_file, 'spcomp', sp_file)
107+
build.newline()
108+
109+
build.comment("""Copy plugin sources to build output""")
110+
for plugin in plugins:
111+
sp_file = os.path.normpath(os.path.join('$root', 'scripting', plugin))
112+
113+
dist_sp = os.path.normpath(os.path.join('$builddir', 'scripting', plugin))
114+
build.build(dist_sp, 'copy', sp_file)
115+
build.newline()
116+
117+
build.comment("""Copy other files from source tree""")
118+
for filepath in copy_files:
119+
build.build(os.path.normpath(os.path.join('$builddir', filepath)), 'copy',
120+
os.path.normpath(os.path.join('$root', filepath)))

Diff for: misc/ninja_syntax.py

+183
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
#!/usr/bin/python
2+
3+
"""Python module for generating .ninja files.
4+
5+
Note that this is emphatically not a required piece of Ninja; it's
6+
just a helpful utility for build-file-generation systems that already
7+
use Python.
8+
"""
9+
10+
import re
11+
import textwrap
12+
13+
def escape_path(word):
14+
return word.replace('$ ', '$$ ').replace(' ', '$ ').replace(':', '$:')
15+
16+
class Writer(object):
17+
def __init__(self, output, width=78):
18+
self.output = output
19+
self.width = width
20+
21+
def newline(self):
22+
self.output.write('\n')
23+
24+
def comment(self, text):
25+
for line in textwrap.wrap(text, self.width - 2, break_long_words=False,
26+
break_on_hyphens=False):
27+
self.output.write('# ' + line + '\n')
28+
29+
def variable(self, key, value, indent=0):
30+
if value is None:
31+
return
32+
if isinstance(value, list):
33+
value = ' '.join(filter(None, value)) # Filter out empty strings.
34+
self._line('%s = %s' % (key, value), indent)
35+
36+
def pool(self, name, depth):
37+
self._line('pool %s' % name)
38+
self.variable('depth', depth, indent=1)
39+
40+
def rule(self, name, command, description=None, depfile=None,
41+
generator=False, pool=None, restat=False, rspfile=None,
42+
rspfile_content=None, deps=None):
43+
self._line('rule %s' % name)
44+
self.variable('command', command, indent=1)
45+
if description:
46+
self.variable('description', description, indent=1)
47+
if depfile:
48+
self.variable('depfile', depfile, indent=1)
49+
if generator:
50+
self.variable('generator', '1', indent=1)
51+
if pool:
52+
self.variable('pool', pool, indent=1)
53+
if restat:
54+
self.variable('restat', '1', indent=1)
55+
if rspfile:
56+
self.variable('rspfile', rspfile, indent=1)
57+
if rspfile_content:
58+
self.variable('rspfile_content', rspfile_content, indent=1)
59+
if deps:
60+
self.variable('deps', deps, indent=1)
61+
62+
def build(self, outputs, rule, inputs=None, implicit=None, order_only=None,
63+
variables=None, implicit_outputs=None, pool=None):
64+
outputs = as_list(outputs)
65+
out_outputs = [escape_path(x) for x in outputs]
66+
all_inputs = [escape_path(x) for x in as_list(inputs)]
67+
68+
if implicit:
69+
implicit = [escape_path(x) for x in as_list(implicit)]
70+
all_inputs.append('|')
71+
all_inputs.extend(implicit)
72+
if order_only:
73+
order_only = [escape_path(x) for x in as_list(order_only)]
74+
all_inputs.append('||')
75+
all_inputs.extend(order_only)
76+
if implicit_outputs:
77+
implicit_outputs = [escape_path(x)
78+
for x in as_list(implicit_outputs)]
79+
out_outputs.append('|')
80+
out_outputs.extend(implicit_outputs)
81+
82+
self._line('build %s: %s' % (' '.join(out_outputs),
83+
' '.join([rule] + all_inputs)))
84+
if pool is not None:
85+
self._line(' pool = %s' % pool)
86+
87+
if variables:
88+
if isinstance(variables, dict):
89+
iterator = iter(variables.items())
90+
else:
91+
iterator = iter(variables)
92+
93+
for key, val in iterator:
94+
self.variable(key, val, indent=1)
95+
96+
return outputs
97+
98+
def include(self, path):
99+
self._line('include %s' % path)
100+
101+
def subninja(self, path):
102+
self._line('subninja %s' % path)
103+
104+
def default(self, paths):
105+
self._line('default %s' % ' '.join(as_list(paths)))
106+
107+
def _count_dollars_before_index(self, s, i):
108+
"""Returns the number of '$' characters right in front of s[i]."""
109+
dollar_count = 0
110+
dollar_index = i - 1
111+
while dollar_index > 0 and s[dollar_index] == '$':
112+
dollar_count += 1
113+
dollar_index -= 1
114+
return dollar_count
115+
116+
def _line(self, text, indent=0):
117+
"""Write 'text' word-wrapped at self.width characters."""
118+
leading_space = ' ' * indent
119+
while len(leading_space) + len(text) > self.width:
120+
# The text is too wide; wrap if possible.
121+
122+
# Find the rightmost space that would obey our width constraint and
123+
# that's not an escaped space.
124+
available_space = self.width - len(leading_space) - len(' $')
125+
space = available_space
126+
while True:
127+
space = text.rfind(' ', 0, space)
128+
if (space < 0 or
129+
self._count_dollars_before_index(text, space) % 2 == 0):
130+
break
131+
132+
if space < 0:
133+
# No such space; just use the first unescaped space we can find.
134+
space = available_space - 1
135+
while True:
136+
space = text.find(' ', space + 1)
137+
if (space < 0 or
138+
self._count_dollars_before_index(text, space) % 2 == 0):
139+
break
140+
if space < 0:
141+
# Give up on breaking.
142+
break
143+
144+
self.output.write(leading_space + text[0:space] + ' $\n')
145+
text = text[space+1:]
146+
147+
# Subsequent lines are continuations, so indent them.
148+
leading_space = ' ' * (indent+2)
149+
150+
self.output.write(leading_space + text + '\n')
151+
152+
def close(self):
153+
self.output.close()
154+
155+
156+
def as_list(input):
157+
if input is None:
158+
return []
159+
if isinstance(input, list):
160+
return input
161+
return [input]
162+
163+
164+
def escape(string):
165+
"""Escape a string such that it can be embedded into a Ninja file without
166+
further interpretation."""
167+
assert '\n' not in string, 'Ninja syntax does not allow newlines'
168+
# We only have one special metacharacter: '$'.
169+
return string.replace('$', '$$')
170+
171+
172+
def expand(string, vars, local_vars={}):
173+
"""Expand a string containing $vars as Ninja would.
174+
175+
Note: doesn't handle the full Ninja variable syntax, but it's enough
176+
to make configure.py's use of it work.
177+
"""
178+
def exp(m):
179+
var = m.group(1)
180+
if var == '$':
181+
return '$'
182+
return local_vars.get(var, vars.get(var, ''))
183+
return re.sub(r'\$(\$|\w*)', exp, string)

Diff for: misc/spcomp_util.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
#!/usr/bin/python3
2+
3+
import subprocess
4+
import io
5+
6+
def extract_version(spcomp):
7+
"""
8+
Extract version string from caption in SourcePawn compiler into a tuple.
9+
The string is hardcoded in `setcaption(void)` in `sourcepawn/compiler/parser.cpp`
10+
"""
11+
p = subprocess.Popen([spcomp], stdout=subprocess.PIPE)
12+
caption = io.TextIOWrapper(p.stdout, encoding="utf-8").readline()
13+
14+
# extracts last element from output in format "SourcePawn Compiler major.minor.rev.patch"
15+
*_, version = caption.split()
16+
return tuple(map(int, version.split('.')))

Diff for: third_party/vendored/stocksoup

Submodule stocksoup added at 541440d

0 commit comments

Comments
 (0)