/
build.py
187 lines (163 loc) · 6.02 KB
/
build.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Configures system-specifc settings and runs `make` to build libtomopy on the
current system.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import os
from os.path import join as pjoin
import logging
import sys
import subprocess
import time
import logging
import argparse
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
if 'CONDA_PREFIX' in os.environ:
PREFIX = os.environ['CONDA_PREFIX']
else:
PREFIX = sys.prefix
INSTALL_PREFIX = None
def get_makefile():
"""Get the Makefile for the system"""
if sys.platform.lower().startswith('win'):
return 'Makefile.windows'
elif sys.platform == 'darwin':
return 'Makefile.darwin'
else:
return 'Makefile.linux'
def build_libtomopy():
"""Build libtomopy shared library for the current system.
This does the following steps:
1. write `Mk.config` for current os
2. run `make -j4` for the the current os
"""
if sys.platform.lower().startswith('win'):
conf = config_windows()
elif sys.platform == 'darwin':
conf = config_macosx()
else:
conf = config_linux()
logger.info("Config output:\n" + conf)
with open('Mk.config', 'w') as fout:
fout.write(conf)
cmd = ['make', '-j4', '-f', get_makefile()]
_PREFIX_PATH = os.path.abspath(INSTALL_PREFIX)
_BINARY_PATH = os.path.abspath(os.path.join(os.getcwd(), ".."))
if INSTALL_PREFIX is not None and _PREFIX_PATH != _BINARY_PATH:
cmd.append('install')
subprocess.check_call(tuple(cmd))
def clean_libtomopy():
"""Clean libtomopy shared library for the current system."""
if os.path.exists(os.path.join(os.getcwd(), "Mk.config")):
subprocess.check_call(('make', 'clean', '-f', get_makefile()))
else:
print("Mk.config does not exist. Assuming nothing to clean...")
class Config:
"""A string formatter for the Makefile"""
def __init__(self):
self.compilerdir = 'gcc'
self.sharedlib = ''
self.arch_target = ''
self.conda_compat = ''
self.includes = [pjoin(os.path.dirname(os.getcwd()), 'include')]
self.linklibs = ['%s' % pjoin(PREFIX, 'lib')]
# anaconda compat?
if 'conda' in sys.version:
compat = pjoin(PREFIX, 'compiler_compat')
if os.path.exists(compat) and os.path.isdir(compat):
self.conda_compat = '-B %s' % compat
if 'GCC' in os.environ:
self.compilerdir = os.environ["GCC"]
# CC environment variable is standard, not GCC
if 'CC' in os.environ:
self.compilerdir = os.environ["CC"]
print("### Compiler set via CC environment variable: '{}'".format(
self.compilerdir))
# includes
top_include = pjoin(PREFIX, 'include')
includes = [top_include]
for fname in os.listdir(top_include):
tdir = pjoin(top_include, fname)
if os.path.isdir(tdir) and 'python' in fname:
includes.append(tdir)
self.includes += includes
def format(self):
"""Return the formatted string, replacing Windows \\ with Unix /."""
include = ' '.join(['-I%s' % s for s in self.includes])
linklib = ' '.join(['-L%s' % s for s in self.linklibs])
buff = ['## generated by build.py %s' % time.ctime(),
'COMPILER_DIR = %s' % self.compilerdir,
'SHAREDLIB = %s' % self.sharedlib,
'ARCH_TARGET = %s' % self.arch_target,
'LINK_LIB = %s' % linklib,
'INCLUDE = %s' % include,
'CONDA_COMPAT = %s' % self.conda_compat,
'INSTALL_PREFIX = %s' % INSTALL_PREFIX,
'####', '']
return '\n'.join(buff).replace('\\', '/')
def config_linux():
"""config for Linux"""
logger.info("Config for Linux")
config = Config()
config.sharedlib = 'libtomopy.so'
return config.format()
def config_macosx():
"""config for MacOSX"""
logger.info("Config for MacOS")
config = Config()
config.sharedlib = 'libtomopy.dylib'
config.arch_target = '-arch x86_64'
return config.format()
def config_windows():
"""config for Windows"""
logger.info("Config for Windows")
config = Config()
compilerdir = None
if 'conda' in sys.version:
# Look for GCC in the conda directory
mingw_path = pjoin(PREFIX, 'MinGW', 'bin')
mingw_gcc = pjoin(mingw_path, 'gcc.exe')
if os.path.exists(mingw_gcc):
logger.info("COMPILER_DIR is {}".format(mingw_gcc))
compilerdir = mingw_path
else:
logger.warn("Compiler not found at {}".format(mingw_gcc))
if compilerdir is None:
for pdir in os.environ['PATH'].split(';'):
gcc = pjoin(pdir, 'gcc.exe')
if os.path.exists(gcc):
compilerdir = pdir
logger.info("COMPILER_DIR is {}".format(pdir))
break
if compilerdir is not None:
config.compilerdir = compilerdir
config.sharedlib = 'libtomopy.dll'
config.includes += [pjoin(PREFIX, 'Library', 'include')]
config.linklibs = [PREFIX,
pjoin(PREFIX, 'Library', 'bin'),
os.path.dirname(os.path.dirname(PREFIX)),
"C:/Windows/System32",
]
return config.format()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--clean",
help="Clean build of TomoPy",
action='store_true')
parser.add_argument("-p", "--prefix",
help="Install prefix",
type=str, default=None)
args = parser.parse_args()
curpath = os.getcwd()
os.chdir('config')
if args.prefix is not None:
INSTALL_PREFIX = args.prefix
if args.clean:
clean_libtomopy()
else:
build_libtomopy()
os.chdir(curpath)