Skip to content

Commit 9b33264

Browse files
authored
Merge pull request #52 from tbenthompson/linting_ci
CI pipeline and linting
2 parents 00c40d9 + d6733ab commit 9b33264

File tree

15 files changed

+322
-193
lines changed

15 files changed

+322
-193
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
name: Lint and Test
2+
3+
on: [push]
4+
5+
jobs:
6+
build-linux:
7+
runs-on: ubuntu-latest
8+
strategy:
9+
max-parallel: 5
10+
11+
steps:
12+
- uses: actions/checkout@v2
13+
- name: Set up Python 3.8
14+
uses: actions/setup-python@v2
15+
with:
16+
python-version: 3.8
17+
- name: Add conda to system path
18+
run: |
19+
# $CONDA is an environment variable pointing to the root of the miniconda directory
20+
echo $CONDA/bin >> $GITHUB_PATH
21+
- name: Install dependencies
22+
run: |
23+
conda env update --file environment.yml --name base
24+
- name: Lint with flake8
25+
run: |
26+
flake8 .
27+
- name: Check formatting with black
28+
run: |
29+
black .
30+
- name: Test with pytest
31+
run: |
32+
pip install --no-use-pep517 --no-deps --disable-pip-version-check -e .
33+
py.test
34+

cppimport/__init__.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
1-
from cppimport.config import set_quiet, force_rebuild, file_exts,\
2-
turn_off_strict_prototypes, set_rtld_flags
1+
from cppimport.config import (
2+
set_quiet,
3+
force_rebuild,
4+
file_exts,
5+
turn_off_strict_prototypes,
6+
set_rtld_flags,
7+
)
38
from cppimport.importer import imp, imp_from_filepath, build
49
from cppimport.templating import setup_pybind11
510
from cppimport.importer import imp as cppimport

cppimport/build_module.py

Lines changed: 53 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
else:
1717
import io
1818

19+
1920
@contextlib.contextmanager
2021
def stdchannel_redirected(stdchannel):
2122
"""
@@ -30,13 +31,15 @@ def stdchannel_redirected(stdchannel):
3031
finally:
3132
setattr(sys, stdchannel, old)
3233

34+
3335
# Subclass setuptools Extension to add a parameter specifying where the shared
3436
# library should be placed after being compiled
3537
class ImportCppExt(setuptools.Extension):
3638
def __init__(self, libdest, *args, **kwargs):
3739
self.libdest = libdest
3840
setuptools.Extension.__init__(self, *args, **kwargs)
3941

42+
4043
# Subclass setuptools build_ext to put the compiled shared library in the
4144
# appropriate place in the source tree.
4245
class BuildImportCppExt(setuptools.command.build_ext.build_ext):
@@ -48,15 +51,23 @@ def copy_extensions_to_source(self):
4851
dest_filename = os.path.join(ext.libdest, os.path.basename(filename))
4952

5053
distutils.file_util.copy_file(
51-
src_filename, dest_filename,
52-
verbose = self.verbose, dry_run = self.dry_run
54+
src_filename, dest_filename, verbose=self.verbose, dry_run=self.dry_run
5355
)
5456

57+
5558
# Patch for parallel compilation with distutils
56-
# From: http://stackoverflow.com/questions/11013851/speeding-up-build-process-with-distutils
57-
def parallel_compile(self, sources, output_dir = None, macros = None,
58-
include_dirs = None, debug = 0, extra_preargs = None, extra_postargs = None,
59-
depends = None):
59+
# From: http://stackoverflow.com/questions/11013851/speeding-up-build-process-with-distutils # noqa: E501
60+
def parallel_compile(
61+
self,
62+
sources,
63+
output_dir=None,
64+
macros=None,
65+
include_dirs=None,
66+
debug=0,
67+
extra_preargs=None,
68+
extra_postargs=None,
69+
depends=None,
70+
):
6071

6172
# these lines are copied directly from distutils.ccompiler.CCompiler
6273
macros, objects, extra_postargs, pp_opts, build = self._setup_compile(
@@ -70,6 +81,7 @@ def parallel_compile(self, sources, output_dir = None, macros = None,
7081
try:
7182
import multiprocessing
7283
import multiprocessing.pool
84+
7385
N = multiprocessing.cpu_count()
7486
except (ImportError, NotImplementedError):
7587
pass
@@ -86,68 +98,66 @@ def _single_compile(obj):
8698
# print("took " + str(end - start) + " to compile " + str(obj))
8799

88100
# imap is evaluated on demand, converting to list() forces execution
89-
list(multiprocessing.pool.ThreadPool(N).imap(_single_compile,objects))
101+
list(multiprocessing.pool.ThreadPool(N).imap(_single_compile, objects))
90102
return objects
91103

104+
92105
def build_module(module_data):
93106
build_path = tempfile.mkdtemp()
94107

95-
full_module_name = module_data['fullname']
96-
filepath = module_data['filepath']
97-
cfg = module_data['cfg']
108+
full_module_name = module_data["fullname"]
109+
filepath = module_data["filepath"]
110+
cfg = module_data["cfg"]
98111

99-
module_data['abs_include_dirs'] = [
100-
make_absolute(module_data['filedirname'], d)
101-
for d in cfg.get('include_dirs', [])
112+
module_data["abs_include_dirs"] = [
113+
make_absolute(module_data["filedirname"], d)
114+
for d in cfg.get("include_dirs", [])
102115
] + [os.path.dirname(filepath)]
103-
module_data['abs_library_dirs'] = [
104-
make_absolute(module_data['filedirname'], d)
105-
for d in cfg.get('library_dirs', [])
116+
module_data["abs_library_dirs"] = [
117+
make_absolute(module_data["filedirname"], d)
118+
for d in cfg.get("library_dirs", [])
106119
]
107-
module_data['dependency_dirs'] = (
108-
module_data['abs_include_dirs'] + [module_data['filedirname']]
109-
)
110-
module_data['extra_source_filepaths'] = [
111-
make_absolute(module_data['filedirname'], s)
112-
for s in cfg.get('sources', [])
120+
module_data["dependency_dirs"] = module_data["abs_include_dirs"] + [
121+
module_data["filedirname"]
122+
]
123+
module_data["extra_source_filepaths"] = [
124+
make_absolute(module_data["filedirname"], s) for s in cfg.get("sources", [])
113125
]
114126

115127
ext = ImportCppExt(
116128
os.path.dirname(filepath),
117129
full_module_name,
118-
language = 'c++',
119-
sources = (
120-
module_data['extra_source_filepaths'] +
121-
[module_data['rendered_src_filepath']]
130+
language="c++",
131+
sources=(
132+
module_data["extra_source_filepaths"]
133+
+ [module_data["rendered_src_filepath"]]
122134
),
123-
include_dirs = module_data['abs_include_dirs'],
124-
extra_compile_args = cfg.get('extra_compile_args', []),
125-
extra_link_args = cfg.get('extra_link_args', []),
126-
library_dirs = module_data['abs_library_dirs'],
127-
libraries = cfg.get('libraries', [])
135+
include_dirs=module_data["abs_include_dirs"],
136+
extra_compile_args=cfg.get("extra_compile_args", []),
137+
extra_link_args=cfg.get("extra_link_args", []),
138+
library_dirs=module_data["abs_library_dirs"],
139+
libraries=cfg.get("libraries", []),
128140
)
129141

130-
args = ['build_ext', '--inplace']
131-
args.append('--build-temp=' + build_path)
132-
args.append('--build-lib=' + build_path)
142+
args = ["build_ext", "--inplace"]
143+
args.append("--build-temp=" + build_path)
144+
args.append("--build-lib=" + build_path)
133145

134146
if cppimport.config.quiet:
135-
args.append('-q')
147+
args.append("-q")
136148
else:
137-
args.append('-v')
149+
args.append("-v")
138150

139151
setuptools_args = dict(
140-
name = full_module_name,
141-
ext_modules = [ext],
142-
script_args = args,
143-
cmdclass = {
144-
'build_ext': BuildImportCppExt
145-
}
152+
name=full_module_name,
153+
ext_modules=[ext],
154+
script_args=args,
155+
cmdclass={"build_ext": BuildImportCppExt},
146156
)
147157

148158
# Monkey patch in the parallel compiler if requested.
149159
py33orgreater = sys.version_info[0] >= 3 and sys.version_info[1] >= 3
150-
parallelize = cfg.get('parallel') and py33orgreater
160+
parallelize = cfg.get("parallel") and py33orgreater
151161
if parallelize:
152162
old_compile = distutils.ccompiler.CCompiler.compile
153163
distutils.ccompiler.CCompiler.compile = parallel_compile

cppimport/checksum.py

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,25 +7,28 @@
77
from cppimport.filepaths import make_absolute
88

99

10-
_TAG = b'cppimport'
11-
_FMT = struct.Struct('q' + str(len(_TAG)) + 's')
10+
_TAG = b"cppimport"
11+
_FMT = struct.Struct("q" + str(len(_TAG)) + "s")
12+
1213

1314
def calc_cur_checksum(file_lst, module_data):
1415
text = b""
1516
for filepath in file_lst:
1617
try:
17-
with open(filepath, 'rb') as f:
18+
with open(filepath, "rb") as f:
1819
text += f.read()
1920
except OSError as e:
2021
cppimport.config.quiet_print(
2122
"Checksummed file not found while checking cppimport checksum "
22-
"(%s); rebuilding." % e)
23+
"(%s); rebuilding." % e
24+
)
2325
return None
2426
return hashlib.md5(text).hexdigest()
2527

28+
2629
def load_checksum_trailer(module_data):
2730
try:
28-
with open(module_data['ext_path'], 'rb') as f:
31+
with open(module_data["ext_path"], "rb") as f:
2932
f.seek(-_FMT.size, 2)
3033
json_len, tag = _FMT.unpack(f.read(_FMT.size))
3134
if tag != _TAG:
@@ -42,33 +45,37 @@ def load_checksum_trailer(module_data):
4245
except ValueError:
4346
cppimport.config.quiet_print(
4447
"Failed to load checksum trailer info from already existing "
45-
"compiled extension; rebuilding.")
48+
"compiled extension; rebuilding."
49+
)
4650
return None, None
4751
return deps, old_checksum
4852

53+
4954
# Use a checksum to see if the file has been changed since the last compilation
5055
def is_checksum_current(module_data):
5156
deps, old_checksum = load_checksum_trailer(module_data)
5257
if old_checksum is None:
5358
return False # Already logged error in load_checksum_trailer.
5459
return old_checksum == calc_cur_checksum(deps, module_data)
5560

61+
5662
def save_checksum_trailer(module_data, dep_filepaths, cur_checksum):
5763
# We can just append the checksum to the shared object; this is effectively
5864
# legal (see e.g. https://stackoverflow.com/questions/10106447).
59-
dump = json.dumps([dep_filepaths, cur_checksum]).encode('ascii')
65+
dump = json.dumps([dep_filepaths, cur_checksum]).encode("ascii")
6066
dump += _FMT.pack(len(dump), _TAG)
61-
with open(module_data['ext_path'], 'ab') as file:
67+
with open(module_data["ext_path"], "ab") as file:
6268
file.write(dump)
6369

70+
6471
def checksum_save(module_data):
6572
dep_filepaths = (
6673
[
67-
make_absolute(module_data['filedirname'], d)
68-
for d in module_data['cfg'].get('dependencies', [])
69-
] +
70-
module_data['extra_source_filepaths'] +
71-
[module_data['filepath']]
74+
make_absolute(module_data["filedirname"], d)
75+
for d in module_data["cfg"].get("dependencies", [])
76+
]
77+
+ module_data["extra_source_filepaths"]
78+
+ [module_data["filepath"]]
7279
)
7380
cur_checksum = calc_cur_checksum(dep_filepaths, module_data)
7481
save_checksum_trailer(module_data, dep_filepaths, cur_checksum)

cppimport/config.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,29 +2,35 @@
22

33
quiet = True
44
should_force_rebuild = False
5-
file_exts = ['.cpp', '.c']
5+
file_exts = [".cpp", ".c"]
66
rtld_flags = ctypes.RTLD_LOCAL
77

8+
89
def set_quiet(to):
910
global quiet
1011
quiet = to
1112

12-
def force_rebuild(to = True):
13+
14+
def force_rebuild(to=True):
1315
global should_force_rebuild
1416
should_force_rebuild = to
1517

18+
1619
def quiet_print(a):
1720
global quiet
1821
if not quiet:
1922
print(a)
2023

24+
2125
def turn_off_strict_prototypes():
2226
import distutils.sysconfig
27+
2328
cfg_vars = distutils.sysconfig.get_config_vars()
2429
for key, value in cfg_vars.items():
2530
if type(value) == str:
2631
cfg_vars[key] = value.replace("-Wstrict-prototypes", "")
2732

33+
2834
def set_rtld_flags(flags):
2935
global rtld_flags
3036
rtld_flags = flags

cppimport/cpprun.py

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import time
21
import os
32
import sys
43
import argparse
@@ -21,17 +20,16 @@
2120

2221

2322
def cpp_run():
24-
parser = argparse.ArgumentParser(description='Run a C++ file with cppimport')
25-
parser.add_argument('filename', help = 'The file to run.')
23+
parser = argparse.ArgumentParser(description="Run a C++ file with cppimport")
24+
parser.add_argument("filename", help="The file to run.")
2625
parser.add_argument(
27-
'--add_main_caller', '-m',
28-
action = 'store_true',
29-
help = 'Add a pybind11 function that will call your main()'
26+
"--add_main_caller",
27+
"-m",
28+
action="store_true",
29+
help="Add a pybind11 function that will call your main()",
3030
)
3131
parser.add_argument(
32-
'--verbose', '-v',
33-
action = 'store_true',
34-
help = 'Tell me everything!'
32+
"--verbose", "-v", action="store_true", help="Tell me everything!"
3533
)
3634
args = parser.parse_args()
3735

@@ -44,11 +42,11 @@ def cpp_run():
4442
module_name, file_extension = os.path.splitext(filebasename)
4543

4644
if args.add_main_caller:
47-
cpprun_dir = '.cpprunfiles'
45+
cpprun_dir = ".cpprunfiles"
4846
if not os.path.exists(cpprun_dir):
4947
os.makedirs(cpprun_dir)
5048
src = os.path.join(cpprun_dir, filebasename)
51-
open(src, 'w').write(open(filename, 'r').read() + footer)
49+
open(src, "w").write(open(filename, "r").read() + footer)
5250
sys.path.append(cpprun_dir)
5351
else:
5452
sys.path.append(filedir)
@@ -60,5 +58,5 @@ def cpp_run():
6058
module.main()
6159

6260

63-
if __name__ == '__main__':
61+
if __name__ == "__main__":
6462
cpp_run()

cppimport/filepaths.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import os
22

3+
34
def make_absolute(this_dir, s):
45
if os.path.isabs(s):
56
return s

0 commit comments

Comments
 (0)