Add support for apu-config.
[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 svn_build_data():
97     """Determine the Subversion header file location."""
98     if "SVN_HEADER_PATH" in os.environ and "SVN_LIBRARY_PATH" in os.environ:
99         return ([os.getenv("SVN_HEADER_PATH")], [os.getenv("SVN_LIBRARY_PATH")], [])
100     svn_prefix = os.getenv("SVN_PREFIX")
101     if svn_prefix is None:
102         basedirs = ["/usr/local", "/usr"]
103         for basedir in basedirs:
104             includedir = os.path.join(basedir, "include/subversion-1")
105             if os.path.isdir(includedir):
106                 svn_prefix = basedir
107                 break
108     if svn_prefix is not None:
109         return ([os.path.join(svn_prefix, "include/subversion-1")], 
110                 [os.path.join(svn_prefix, "lib")], [])
111     raise Exception("Subversion development files not found. "
112                     "Please set SVN_PREFIX or (SVN_LIBRARY_PATH and SVN_HEADER_PATH) environment variable. ")
113
114 def is_keychain_provider_available():
115     """
116     Checks for the availability of the Keychain simple authentication provider in Subversion by compiling a simple test program.
117     """
118     abd = apr_build_data()
119     sbd = svn_build_data()
120     gcc_command_args = ['gcc'] + ['-I' + inc for inc in sbd[0]] + ['-L' + lib for lib in sbd[1]] + ['-I' + abd[0], '-lsvn_subr-1', '-x', 'c', '-']
121     (gcc_in, gcc_out, gcc_err) = os.popen3(gcc_command_args)
122     gcc_in.write("""
123 #include <svn_auth.h>
124 int main(int argc, const char* arv[]) {
125     svn_auth_get_keychain_simple_provider(NULL, NULL);
126 }
127 """)
128     gcc_in.close()
129     gcc_out.read()
130     return (gcc_out.close() is None)
131
132 class VersionQuery(object):
133     def __init__(self, filename):
134         self.filename = filename
135         f = file(filename, "rU")
136         try:
137             self.text = f.read()
138         finally:
139             f.close()
140
141     def grep(self, what):
142         m = re.search(r"^#define\s+%s\s+(\d+)\s*$" % (what,), self.text, re.MULTILINE)
143         if not m:
144             raise Exception("Definition for %s was not found in file %s." % (what, self.filename))
145         return int(m.group(1))
146
147 # Windows versions - we use environment variables to locate the directories
148 # and hard-code a list of libraries.
149 if os.name == "nt":
150     def get_apr_version():
151         apr_version_file = os.path.join(os.environ["SVN_DEV"], r"include\apr\apr_version.h")
152         if not os.path.isfile(apr_version_file):
153             raise Exception(
154                 "Please check that your SVN_DEV location is correct.\n"
155                 "Unable to find required apr\\apr_version.h file.")
156         query = VersionQuery(apr_version_file)
157         return query.grep("APR_MAJOR_VERSION"), query.grep("APR_MINOR_VERSION"), query.grep("APR_PATCH_VERSION")
158
159     def get_svn_version():
160         svn_version_file = os.path.join(os.environ["SVN_DEV"], r"include\svn_version.h")
161         if not os.path.isfile(svn_version_file):
162             raise Exception(
163                 "Please check that your SVN_DEV location is correct.\n"
164                 "Unable to find required svn_version.h file.")
165         query = VersionQuery(svn_version_file)
166         return query.grep("SVN_VER_MAJOR"), query.grep("SVN_VER_MINOR"), query.grep("SVN_VER_PATCH")
167
168     # just clobber the functions above we can't use
169     # for simplicitly, everything is done in the 'svn' one
170     def apr_build_data():
171         return '.', 
172
173     def svn_build_data():
174         # environment vars for the directories we need.
175         svn_dev_dir = os.environ.get("SVN_DEV")
176         if not svn_dev_dir or not os.path.isdir(svn_dev_dir):
177             raise Exception(
178                 "Please set SVN_DEV to the location of the svn development "
179                 "packages.\nThese can be downloaded from:\n"
180                 "http://subversion.tigris.org/servlets/ProjectDocumentList?folderID=91")
181         svn_bdb_dir = os.environ.get("SVN_BDB")
182         if not svn_bdb_dir or not os.path.isdir(svn_bdb_dir):
183             raise Exception(
184                 "Please set SVN_BDB to the location of the svn BDB packages "
185                 "- see README.txt in the SV_DEV dir")
186         svn_libintl_dir = os.environ.get("SVN_LIBINTL")
187         if not svn_libintl_dir or not os.path.isdir(svn_libintl_dir):
188             raise Exception(
189                 "Please set SVN_LIBINTL to the location of the svn libintl "
190                 "packages - see README.txt in the SV_DEV dir")
191
192         svn_version = get_svn_version()
193         apr_version = get_apr_version()
194
195         includes = [
196             # apr dirs.
197             os.path.join(svn_dev_dir, r"include\apr"),
198             os.path.join(svn_dev_dir, r"include\apr-util"),
199             os.path.join(svn_dev_dir, r"include\apr-iconv"),
200             # svn dirs.
201             os.path.join(svn_dev_dir, "include"), 
202         ]
203         lib_dirs = [
204             os.path.join(svn_dev_dir, "lib"),
205             os.path.join(svn_dev_dir, "lib", "apr"),
206             os.path.join(svn_dev_dir, "lib", "apr-iconv"),
207             os.path.join(svn_dev_dir, "lib", "apr-util"),
208             os.path.join(svn_dev_dir, "lib", "neon"),
209             os.path.join(svn_bdb_dir, "lib"),
210             os.path.join(svn_libintl_dir, "lib"),
211         ]
212         aprlibs = """libapr libapriconv libaprutil""".split()
213         if apr_version[0] == 1:
214             aprlibs = [aprlib + "-1" for aprlib in aprlibs]
215         elif apr_version[0] > 1:
216             raise Exception(
217                 "You have apr version %d.%d.%d.\n"
218                 "This setup only knows how to build with 0.*.* or 1.*.*." % apr_version)
219         libs = """libneon libsvn_subr-1 libsvn_client-1 libsvn_ra-1
220                   libsvn_ra_dav-1 libsvn_ra_local-1 libsvn_ra_svn-1
221                   libsvn_repos-1 libsvn_wc-1 libsvn_delta-1 libsvn_diff-1
222                   libsvn_fs-1 libsvn_repos-1 libsvn_fs_fs-1 libsvn_fs_base-1
223                   intl3_svn
224                   libdb44 xml
225                   advapi32 shell32 ws2_32 zlibstat
226                """.split()
227         if svn_version >= (1,5,0):
228             # Since 1.5.0 libsvn_ra_dav-1 was removed
229             libs.remove("libsvn_ra_dav-1")
230
231         return includes, lib_dirs, aprlibs+libs,
232
233 (apr_includedir, ) = apr_build_data()
234 (svn_includedirs, svn_libdirs, extra_libs) = svn_build_data()
235
236 def SvnExtension(name, *args, **kwargs):
237     kwargs["include_dirs"] = [apr_includedir] + svn_includedirs + ["subvertpy"]
238     kwargs["library_dirs"] = svn_libdirs
239     if os.name == 'nt':
240         # on windows, just ignore and overwrite the libraries!
241         kwargs["libraries"] = extra_libs
242         # APR needs WIN32 defined.
243         kwargs["define_macros"] = [("WIN32", None)]
244     if sys.platform == 'darwin':
245         # on Mac OS X, we need to check for Keychain availability
246         if is_keychain_provider_available():
247             if "define_macros" not in kwargs:
248                 kwargs["define_macros"] = []
249             kwargs["define_macros"].extend((('DARWIN', None), ('SVN_KEYCHAIN_PROVIDER_AVAILABLE', '1')))
250     return Extension(name, *args, **kwargs)
251
252
253 # On Windows, we install the apr binaries too.
254 class install_lib_with_dlls(install_lib):
255     def _get_dlls(self):
256         # return a list of of (FQ-in-name, relative-out-name) tuples.
257         ret = []
258         apr_bins = [libname + ".dll" for libname in extra_libs if libname.startswith("libapr")]
259         if get_svn_version() >= (1,5,0):
260             # Since 1.5.0 these libraries became shared
261             apr_bins += """libsvn_client-1.dll libsvn_delta-1.dll libsvn_diff-1.dll
262                            libsvn_fs-1.dll libsvn_ra-1.dll libsvn_repos-1.dll
263                            libsvn_subr-1.dll libsvn_wc-1.dll libsasl.dll""".split()
264         apr_bins += """intl3_svn.dll libdb44.dll libeay32.dll ssleay32.dll""".split()
265         look_dirs = os.environ.get("PATH","").split(os.pathsep)
266         look_dirs.insert(0, os.path.join(os.environ["SVN_DEV"], "bin"))
267     
268         for bin in apr_bins:
269             for look in look_dirs:
270                 f = os.path.join(look, bin)
271                 if os.path.isfile(f):
272                     target = os.path.join(self.install_dir, "subvertpy", bin)
273                     ret.append((f, target))
274                     break
275             else:
276                 log.warn("Could not find required DLL %r to include", bin)
277                 log.debug("(looked in %s)", look_dirs)
278         return ret
279
280     def run(self):
281         install_lib.run(self)
282         # the apr binaries.
283         if os.name == 'nt':
284             # On Windows we package up the apr dlls with the plugin.
285             for s, d in self._get_dlls():
286                 self.copy_file(s, d)
287
288     def get_outputs(self):
289         ret = install_lib.get_outputs(self)
290         if os.name == 'nt':
291             ret.extend([info[1] for info in self._get_dlls()])
292         return ret
293
294
295 def source_path(filename):
296     return os.path.join("subvertpy", filename)
297
298
299 def subvertpy_modules():
300     return [
301         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"]), 
302         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"]),
303         SvnExtension("subvertpy.repos", [source_path(n) for n in ("repos.c", "util.c")], libraries=["svn_repos-1", "svn_subr-1"]),
304         SvnExtension("subvertpy.wc", [source_path(n) for n in ("wc.c", "util.c", "editor.c")], libraries=["svn_wc-1", "svn_subr-1"])
305         ]
306
307
308 subvertpy_version = (0, 7, 4)
309 subvertpy_version_string = ".".join(map(str, subvertpy_version))
310
311
312 if __name__ == "__main__":
313     setup(name='subvertpy',
314           description='Alternative Python bindings for Subversion',
315           keywords='plugin svn',
316           version=subvertpy_version_string,
317           url='http://samba.org/~jelmer/subvertpy',
318           download_url="http://samba.org/~jelmer/subvertpy/subvertpy-%s.tar.gz" % subvertpy_version_string,
319           license='LGPLv2.1 or later',
320           author='Jelmer Vernooij',
321           author_email='jelmer@samba.org',
322           long_description="""
323           Alternative Python bindings for Subversion, split out from bzr-svn. The goal is to have complete, portable and "Pythonic" Python bindings. 
324           """,
325           packages=['subvertpy', 'subvertpy.tests'],
326           ext_modules=subvertpy_modules(),
327           scripts=['bin/subvertpy-fast-export'],
328           cmdclass = { 'install_lib': install_lib_with_dlls },
329           )