use apu include directory.
[jelmer/subvertpy.git] / setup.py
1 #!/usr/bin/env python
2 # Setup file for subvertpy
3 # Copyright (C) 2005-2009 Jelmer Vernooij <jelmer@samba.org>
4
5 from distutils.core import setup
6 from distutils.extension import Extension
7 from distutils.command.install_lib import install_lib
8 from distutils import log
9 import sys
10 import os
11 import re
12
13 # Build instructions for Windows:
14 # * Install the SVN dev kit ZIP for Windows from
15 #   http://subversion.tigris.org/servlets/ProjectDocumentList?folderID=91
16 #   At time of writing, this was svn-win32-1.4.6_dev.zip
17 # * Find the SVN binary ZIP file with the binaries for your dev kit.
18 #   At time of writing, this was svn-win32-1.4.6.zip
19 #   Unzip this in the *same directory* as the dev kit - README.txt will be
20 #   overwritten, but that is all. This is the default location the .ZIP file
21 #   will suggest (ie, the directory embedded in both .zip files are the same)
22 # * Set SVN_DEV to point at this directory.
23 # * Install the APR BDB and INTL packages - see README.txt from the devkit
24 # * Set SVN_BDB and SVN_LIBINTL to point at these dirs.
25
26 class CommandException(Exception):
27     """Encapsulate exit status of apr-config execution"""
28     def __init__(self, msg, cmd, arg, status, val):
29         self.message = msg % (cmd, val)
30         Exception.__init__(self, self.message)
31         self.cmd = cmd
32         self.arg = arg
33         self.status = status
34     def not_found(self):
35         return os.WIFEXITED(self.status) and os.WEXITSTATUS(self.status) == 127
36
37
38 def run_cmd(cmd, arg):
39     """Run specified command with given arguments, handling status"""
40     f = os.popen("'%s' %s" % (cmd, arg))
41     dir = f.read().rstrip("\n")
42     status = f.close()
43     if status is None:
44         return dir
45     if os.WIFEXITED(status):
46         code = os.WEXITSTATUS(status)
47         if code == 0:
48             return dir
49         raise CommandException("%s exited with status %d",
50                                cmd, arg, status, code)
51     if os.WIFSIGNALED(status):
52         signal = os.WTERMSIG(status)
53         raise CommandException("%s killed by signal %d",
54                                cmd, arg, status, signal)
55     raise CommandException("%s terminated abnormally (%d)",
56                            cmd, arg, status, status)
57
58
59 def config_value(command, arg):
60     cmds = [command] + [os.path.join(p, command) for p in ["/usr/local/apr/bin/", "/opt/local/bin/"]]
61     for cmd in cmds:
62         try:
63             return run_cmd(cmd, arg)
64         except CommandException, e:
65             if not e.not_found():
66                 raise
67     else:
68         raise Exception("apr-config not found."
69                         " Please set APR_CONFIG environment variable")
70
71
72 def apr_config(arg):
73     config_cmd = os.getenv("APR_CONFIG")
74     if config_cmd is None:
75         return config_value("apr-1-config", arg)
76     else:
77         return run_cmd(config_cmd, arg)
78
79
80 def apu_config(arg):
81     config_cmd = os.getenv("APU_CONFIG")
82     if config_cmd is None:
83         return config_value("apu-config", arg)
84     else:
85         return run_cmd(config_cmd, arg)
86
87
88 def apr_build_data():
89     """Determine the APR header file location."""
90     includedir = apr_config("--includedir")
91     if not os.path.isdir(includedir):
92         raise Exception("APR development headers not found")
93     return (includedir,)
94
95
96 def apu_build_data():
97     """Determine the APR util header file location."""
98     includedir = apu_config("--includedir")
99     if not os.path.isdir(includedir):
100         raise Exception("APR util development headers not found")
101     return (includedir,)
102
103
104 def svn_build_data():
105     """Determine the Subversion header file location."""
106     if "SVN_HEADER_PATH" in os.environ and "SVN_LIBRARY_PATH" in os.environ:
107         return ([os.getenv("SVN_HEADER_PATH")], [os.getenv("SVN_LIBRARY_PATH")], [])
108     svn_prefix = os.getenv("SVN_PREFIX")
109     if svn_prefix is None:
110         basedirs = ["/usr/local", "/usr"]
111         for basedir in basedirs:
112             includedir = os.path.join(basedir, "include/subversion-1")
113             if os.path.isdir(includedir):
114                 svn_prefix = basedir
115                 break
116     if svn_prefix is not None:
117         return ([os.path.join(svn_prefix, "include/subversion-1")], 
118                 [os.path.join(svn_prefix, "lib")], [])
119     raise Exception("Subversion development files not found. "
120                     "Please set SVN_PREFIX or (SVN_LIBRARY_PATH and SVN_HEADER_PATH) environment variable. ")
121
122 def is_keychain_provider_available():
123     """
124     Checks for the availability of the Keychain simple authentication provider in Subversion by compiling a simple test program.
125     """
126     abd = apr_build_data()
127     abud = apu_build_data()
128     sbd = svn_build_data()
129     gcc_command_args = ['gcc'] + ['-I' + inc for inc in sbd[0]] + ['-L' + lib for lib in sbd[1]] + ['-I' + abd[0], '-I' + abud[0], '-lsvn_subr-1', '-x', 'c', '-']
130     (gcc_in, gcc_out, gcc_err) = os.popen3(gcc_command_args)
131     gcc_in.write("""
132 #include <svn_auth.h>
133 int main(int argc, const char* arv[]) {
134     svn_auth_get_keychain_simple_provider(NULL, NULL);
135 }
136 """)
137     gcc_in.close()
138     gcc_out.read()
139     return (gcc_out.close() is None)
140
141 class VersionQuery(object):
142     def __init__(self, filename):
143         self.filename = filename
144         f = file(filename, "rU")
145         try:
146             self.text = f.read()
147         finally:
148             f.close()
149
150     def grep(self, what):
151         m = re.search(r"^#define\s+%s\s+(\d+)\s*$" % (what,), self.text, re.MULTILINE)
152         if not m:
153             raise Exception("Definition for %s was not found in file %s." % (what, self.filename))
154         return int(m.group(1))
155
156 # Windows versions - we use environment variables to locate the directories
157 # and hard-code a list of libraries.
158 if os.name == "nt":
159     def get_apr_version():
160         apr_version_file = os.path.join(os.environ["SVN_DEV"], r"include\apr\apr_version.h")
161         if not os.path.isfile(apr_version_file):
162             raise Exception(
163                 "Please check that your SVN_DEV location is correct.\n"
164                 "Unable to find required apr\\apr_version.h file.")
165         query = VersionQuery(apr_version_file)
166         return query.grep("APR_MAJOR_VERSION"), query.grep("APR_MINOR_VERSION"), query.grep("APR_PATCH_VERSION")
167
168     def get_svn_version():
169         svn_version_file = os.path.join(os.environ["SVN_DEV"], r"include\svn_version.h")
170         if not os.path.isfile(svn_version_file):
171             raise Exception(
172                 "Please check that your SVN_DEV location is correct.\n"
173                 "Unable to find required svn_version.h file.")
174         query = VersionQuery(svn_version_file)
175         return query.grep("SVN_VER_MAJOR"), query.grep("SVN_VER_MINOR"), query.grep("SVN_VER_PATCH")
176
177     # just clobber the functions above we can't use
178     # for simplicitly, everything is done in the 'svn' one
179     def apr_build_data():
180         return '.',
181
182     def apu_build_data():
183         return '.',
184
185     def svn_build_data():
186         # environment vars for the directories we need.
187         svn_dev_dir = os.environ.get("SVN_DEV")
188         if not svn_dev_dir or not os.path.isdir(svn_dev_dir):
189             raise Exception(
190                 "Please set SVN_DEV to the location of the svn development "
191                 "packages.\nThese can be downloaded from:\n"
192                 "http://subversion.tigris.org/servlets/ProjectDocumentList?folderID=91")
193         svn_bdb_dir = os.environ.get("SVN_BDB")
194         if not svn_bdb_dir or not os.path.isdir(svn_bdb_dir):
195             raise Exception(
196                 "Please set SVN_BDB to the location of the svn BDB packages "
197                 "- see README.txt in the SV_DEV dir")
198         svn_libintl_dir = os.environ.get("SVN_LIBINTL")
199         if not svn_libintl_dir or not os.path.isdir(svn_libintl_dir):
200             raise Exception(
201                 "Please set SVN_LIBINTL to the location of the svn libintl "
202                 "packages - see README.txt in the SV_DEV dir")
203
204         svn_version = get_svn_version()
205         apr_version = get_apr_version()
206
207         includes = [
208             # apr dirs.
209             os.path.join(svn_dev_dir, r"include\apr"),
210             os.path.join(svn_dev_dir, r"include\apr-util"),
211             os.path.join(svn_dev_dir, r"include\apr-iconv"),
212             # svn dirs.
213             os.path.join(svn_dev_dir, "include"), 
214         ]
215         lib_dirs = [
216             os.path.join(svn_dev_dir, "lib"),
217             os.path.join(svn_dev_dir, "lib", "apr"),
218             os.path.join(svn_dev_dir, "lib", "apr-iconv"),
219             os.path.join(svn_dev_dir, "lib", "apr-util"),
220             os.path.join(svn_dev_dir, "lib", "neon"),
221             os.path.join(svn_bdb_dir, "lib"),
222             os.path.join(svn_libintl_dir, "lib"),
223         ]
224         aprlibs = """libapr libapriconv libaprutil""".split()
225         if apr_version[0] == 1:
226             aprlibs = [aprlib + "-1" for aprlib in aprlibs]
227         elif apr_version[0] > 1:
228             raise Exception(
229                 "You have apr version %d.%d.%d.\n"
230                 "This setup only knows how to build with 0.*.* or 1.*.*." % apr_version)
231         libs = """libneon libsvn_subr-1 libsvn_client-1 libsvn_ra-1
232                   libsvn_ra_dav-1 libsvn_ra_local-1 libsvn_ra_svn-1
233                   libsvn_repos-1 libsvn_wc-1 libsvn_delta-1 libsvn_diff-1
234                   libsvn_fs-1 libsvn_repos-1 libsvn_fs_fs-1 libsvn_fs_base-1
235                   intl3_svn
236                   libdb44 xml
237                   advapi32 shell32 ws2_32 zlibstat
238                """.split()
239         if svn_version >= (1,5,0):
240             # Since 1.5.0 libsvn_ra_dav-1 was removed
241             libs.remove("libsvn_ra_dav-1")
242
243         return includes, lib_dirs, aprlibs+libs,
244
245 (apr_includedir, ) = apr_build_data()
246 (apu_includedir, ) = apu_build_data()
247 (svn_includedirs, svn_libdirs, extra_libs) = svn_build_data()
248
249 def SvnExtension(name, *args, **kwargs):
250     kwargs["include_dirs"] = [apr_includedir, apu_includedir] + svn_includedirs + ["subvertpy"]
251     kwargs["library_dirs"] = svn_libdirs
252     if os.name == 'nt':
253         # on windows, just ignore and overwrite the libraries!
254         kwargs["libraries"] = extra_libs
255         # APR needs WIN32 defined.
256         kwargs["define_macros"] = [("WIN32", None)]
257     if sys.platform == 'darwin':
258         # on Mac OS X, we need to check for Keychain availability
259         if is_keychain_provider_available():
260             if "define_macros" not in kwargs:
261                 kwargs["define_macros"] = []
262             kwargs["define_macros"].extend((('DARWIN', None), ('SVN_KEYCHAIN_PROVIDER_AVAILABLE', '1')))
263     return Extension(name, *args, **kwargs)
264
265
266 # On Windows, we install the apr binaries too.
267 class install_lib_with_dlls(install_lib):
268     def _get_dlls(self):
269         # return a list of of (FQ-in-name, relative-out-name) tuples.
270         ret = []
271         apr_bins = [libname + ".dll" for libname in extra_libs if libname.startswith("libapr")]
272         if get_svn_version() >= (1,5,0):
273             # Since 1.5.0 these libraries became shared
274             apr_bins += """libsvn_client-1.dll libsvn_delta-1.dll libsvn_diff-1.dll
275                            libsvn_fs-1.dll libsvn_ra-1.dll libsvn_repos-1.dll
276                            libsvn_subr-1.dll libsvn_wc-1.dll libsasl.dll""".split()
277         apr_bins += """intl3_svn.dll libdb44.dll libeay32.dll ssleay32.dll""".split()
278         look_dirs = os.environ.get("PATH","").split(os.pathsep)
279         look_dirs.insert(0, os.path.join(os.environ["SVN_DEV"], "bin"))
280     
281         for bin in apr_bins:
282             for look in look_dirs:
283                 f = os.path.join(look, bin)
284                 if os.path.isfile(f):
285                     target = os.path.join(self.install_dir, "subvertpy", bin)
286                     ret.append((f, target))
287                     break
288             else:
289                 log.warn("Could not find required DLL %r to include", bin)
290                 log.debug("(looked in %s)", look_dirs)
291         return ret
292
293     def run(self):
294         install_lib.run(self)
295         # the apr binaries.
296         if os.name == 'nt':
297             # On Windows we package up the apr dlls with the plugin.
298             for s, d in self._get_dlls():
299                 self.copy_file(s, d)
300
301     def get_outputs(self):
302         ret = install_lib.get_outputs(self)
303         if os.name == 'nt':
304             ret.extend([info[1] for info in self._get_dlls()])
305         return ret
306
307
308 def source_path(filename):
309     return os.path.join("subvertpy", filename)
310
311
312 def subvertpy_modules():
313     return [
314         SvnExtension("subvertpy.client", [source_path(n) for n in ("client.c", "editor.c", "util.c", "_ra.c", "wc.c")], libraries=["svn_client-1", "svn_subr-1"]), 
315         SvnExtension("subvertpy._ra", [source_path(n) for n in ("_ra.c", "util.c", "editor.c")], libraries=["svn_ra-1", "svn_delta-1", "svn_subr-1"]),
316         SvnExtension("subvertpy.repos", [source_path(n) for n in ("repos.c", "util.c")], libraries=["svn_repos-1", "svn_subr-1"]),
317         SvnExtension("subvertpy.wc", [source_path(n) for n in ("wc.c", "util.c", "editor.c")], libraries=["svn_wc-1", "svn_subr-1"])
318         ]
319
320
321 subvertpy_version = (0, 7, 4)
322 subvertpy_version_string = ".".join(map(str, subvertpy_version))
323
324
325 if __name__ == "__main__":
326     setup(name='subvertpy',
327           description='Alternative Python bindings for Subversion',
328           keywords='plugin svn',
329           version=subvertpy_version_string,
330           url='http://samba.org/~jelmer/subvertpy',
331           download_url="http://samba.org/~jelmer/subvertpy/subvertpy-%s.tar.gz" % subvertpy_version_string,
332           license='LGPLv2.1 or later',
333           author='Jelmer Vernooij',
334           author_email='jelmer@samba.org',
335           long_description="""
336           Alternative Python bindings for Subversion, split out from bzr-svn. The goal is to have complete, portable and "Pythonic" Python bindings. 
337           """,
338           packages=['subvertpy', 'subvertpy.tests'],
339           ext_modules=subvertpy_modules(),
340           scripts=['bin/subvertpy-fast-export'],
341           cmdclass = { 'install_lib': install_lib_with_dlls },
342           )