PageRenderTime 49ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/bin/mercurial-1.7.5/setup.py

https://github.com/signalnine/cr48
Python | 391 lines | 300 code | 51 blank | 40 comment | 63 complexity | b468264c359431b04bbf70632bfe572a MD5 | raw file
  1. #
  2. # This is the mercurial setup script.
  3. #
  4. # 'python setup.py install', or
  5. # 'python setup.py --help' for more options
  6. import sys
  7. if not hasattr(sys, 'version_info') or sys.version_info < (2, 4, 0, 'final'):
  8. raise SystemExit("Mercurial requires Python 2.4 or later.")
  9. if sys.version_info[0] >= 3:
  10. def b(s):
  11. '''A helper function to emulate 2.6+ bytes literals using string
  12. literals.'''
  13. return s.encode('latin1')
  14. else:
  15. def b(s):
  16. '''A helper function to emulate 2.6+ bytes literals using string
  17. literals.'''
  18. return s
  19. # Solaris Python packaging brain damage
  20. try:
  21. import hashlib
  22. sha = hashlib.sha1()
  23. except:
  24. try:
  25. import sha
  26. except:
  27. raise SystemExit(
  28. "Couldn't import standard hashlib (incomplete Python install).")
  29. try:
  30. import zlib
  31. except:
  32. raise SystemExit(
  33. "Couldn't import standard zlib (incomplete Python install).")
  34. try:
  35. import bz2
  36. except:
  37. raise SystemExit(
  38. "Couldn't import standard bz2 (incomplete Python install).")
  39. import os, subprocess, time
  40. import shutil
  41. import tempfile
  42. from distutils import log
  43. from distutils.core import setup, Extension
  44. from distutils.dist import Distribution
  45. from distutils.command.build import build
  46. from distutils.command.build_ext import build_ext
  47. from distutils.command.build_py import build_py
  48. from distutils.command.install_scripts import install_scripts
  49. from distutils.spawn import spawn, find_executable
  50. from distutils.ccompiler import new_compiler
  51. from distutils.errors import CCompilerError
  52. from distutils.sysconfig import get_python_inc
  53. scripts = ['hg']
  54. if os.name == 'nt':
  55. scripts.append('contrib/win32/hg.bat')
  56. # simplified version of distutils.ccompiler.CCompiler.has_function
  57. # that actually removes its temporary files.
  58. def hasfunction(cc, funcname):
  59. tmpdir = tempfile.mkdtemp(prefix='hg-install-')
  60. devnull = oldstderr = None
  61. try:
  62. try:
  63. fname = os.path.join(tmpdir, 'funcname.c')
  64. f = open(fname, 'w')
  65. f.write('int main(void) {\n')
  66. f.write(' %s();\n' % funcname)
  67. f.write('}\n')
  68. f.close()
  69. # Redirect stderr to /dev/null to hide any error messages
  70. # from the compiler.
  71. # This will have to be changed if we ever have to check
  72. # for a function on Windows.
  73. devnull = open('/dev/null', 'w')
  74. oldstderr = os.dup(sys.stderr.fileno())
  75. os.dup2(devnull.fileno(), sys.stderr.fileno())
  76. objects = cc.compile([fname], output_dir=tmpdir)
  77. cc.link_executable(objects, os.path.join(tmpdir, "a.out"))
  78. except:
  79. return False
  80. return True
  81. finally:
  82. if oldstderr is not None:
  83. os.dup2(oldstderr, sys.stderr.fileno())
  84. if devnull is not None:
  85. devnull.close()
  86. shutil.rmtree(tmpdir)
  87. # py2exe needs to be installed to work
  88. try:
  89. import py2exe
  90. py2exeloaded = True
  91. # Help py2exe to find win32com.shell
  92. try:
  93. import modulefinder
  94. import win32com
  95. for p in win32com.__path__[1:]: # Take the path to win32comext
  96. modulefinder.AddPackagePath("win32com", p)
  97. pn = "win32com.shell"
  98. __import__(pn)
  99. m = sys.modules[pn]
  100. for p in m.__path__[1:]:
  101. modulefinder.AddPackagePath(pn, p)
  102. except ImportError:
  103. pass
  104. except ImportError:
  105. py2exeloaded = False
  106. pass
  107. def runcmd(cmd, env):
  108. p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
  109. stderr=subprocess.PIPE, env=env)
  110. out, err = p.communicate()
  111. # If root is executing setup.py, but the repository is owned by
  112. # another user (as in "sudo python setup.py install") we will get
  113. # trust warnings since the .hg/hgrc file is untrusted. That is
  114. # fine, we don't want to load it anyway. Python may warn about
  115. # a missing __init__.py in mercurial/locale, we also ignore that.
  116. err = [e for e in err.splitlines()
  117. if not e.startswith(b('Not trusting file')) \
  118. and not e.startswith(b('warning: Not importing'))]
  119. if err:
  120. return ''
  121. return out
  122. version = ''
  123. if os.path.isdir('.hg'):
  124. # Execute hg out of this directory with a custom environment which
  125. # includes the pure Python modules in mercurial/pure. We also take
  126. # care to not use any hgrc files and do no localization.
  127. pypath = ['mercurial', os.path.join('mercurial', 'pure')]
  128. env = {'PYTHONPATH': os.pathsep.join(pypath),
  129. 'HGRCPATH': '',
  130. 'LANGUAGE': 'C'}
  131. if 'LD_LIBRARY_PATH' in os.environ:
  132. env['LD_LIBRARY_PATH'] = os.environ['LD_LIBRARY_PATH']
  133. if 'SystemRoot' in os.environ:
  134. # Copy SystemRoot into the custom environment for Python 2.6
  135. # under Windows. Otherwise, the subprocess will fail with
  136. # error 0xc0150004. See: http://bugs.python.org/issue3440
  137. env['SystemRoot'] = os.environ['SystemRoot']
  138. cmd = [sys.executable, 'hg', 'id', '-i', '-t']
  139. l = runcmd(cmd, env).split()
  140. while len(l) > 1 and l[-1][0].isalpha(): # remove non-numbered tags
  141. l.pop()
  142. if len(l) > 1: # tag found
  143. version = l[-1]
  144. if l[0].endswith('+'): # propagate the dirty status to the tag
  145. version += '+'
  146. elif len(l) == 1: # no tag found
  147. cmd = [sys.executable, 'hg', 'parents', '--template',
  148. '{latesttag}+{latesttagdistance}-']
  149. version = runcmd(cmd, env) + l[0]
  150. if version.endswith('+'):
  151. version += time.strftime('%Y%m%d')
  152. elif os.path.exists('.hg_archival.txt'):
  153. kw = dict([[t.strip() for t in l.split(':', 1)]
  154. for l in open('.hg_archival.txt')])
  155. if 'tag' in kw:
  156. version = kw['tag']
  157. elif 'latesttag' in kw:
  158. version = '%(latesttag)s+%(latesttagdistance)s-%(node).12s' % kw
  159. else:
  160. version = kw.get('node', '')[:12]
  161. if version:
  162. f = open("mercurial/__version__.py", "w")
  163. f.write('# this file is autogenerated by setup.py\n')
  164. f.write('version = "%s"\n' % version)
  165. f.close()
  166. try:
  167. from mercurial import __version__
  168. version = __version__.version
  169. except ImportError:
  170. version = 'unknown'
  171. class hgbuildmo(build):
  172. description = "build translations (.mo files)"
  173. def run(self):
  174. if not find_executable('msgfmt'):
  175. self.warn("could not find msgfmt executable, no translations "
  176. "will be built")
  177. return
  178. podir = 'i18n'
  179. if not os.path.isdir(podir):
  180. self.warn("could not find %s/ directory" % podir)
  181. return
  182. join = os.path.join
  183. for po in os.listdir(podir):
  184. if not po.endswith('.po'):
  185. continue
  186. pofile = join(podir, po)
  187. modir = join('locale', po[:-3], 'LC_MESSAGES')
  188. mofile = join(modir, 'hg.mo')
  189. mobuildfile = join('mercurial', mofile)
  190. cmd = ['msgfmt', '-v', '-o', mobuildfile, pofile]
  191. if sys.platform != 'sunos5':
  192. # msgfmt on Solaris does not know about -c
  193. cmd.append('-c')
  194. self.mkpath(join('mercurial', modir))
  195. self.make_file([pofile], mobuildfile, spawn, (cmd,))
  196. # Insert hgbuildmo first so that files in mercurial/locale/ are found
  197. # when build_py is run next.
  198. build.sub_commands.insert(0, ('build_mo', None))
  199. Distribution.pure = 0
  200. Distribution.global_options.append(('pure', None, "use pure (slow) Python "
  201. "code instead of C extensions"))
  202. class hgbuildext(build_ext):
  203. def build_extension(self, ext):
  204. try:
  205. build_ext.build_extension(self, ext)
  206. except CCompilerError:
  207. if not getattr(ext, 'optional', False):
  208. raise
  209. log.warn("Failed to build optional extension '%s' (skipping)",
  210. ext.name)
  211. class hgbuildpy(build_py):
  212. def finalize_options(self):
  213. build_py.finalize_options(self)
  214. if self.distribution.pure:
  215. if self.py_modules is None:
  216. self.py_modules = []
  217. for ext in self.distribution.ext_modules:
  218. if ext.name.startswith("mercurial."):
  219. self.py_modules.append("mercurial.pure.%s" % ext.name[10:])
  220. self.distribution.ext_modules = []
  221. else:
  222. if not os.path.exists(os.path.join(get_python_inc(), 'Python.h')):
  223. raise SystemExit("Python headers are required to build Mercurial")
  224. def find_modules(self):
  225. modules = build_py.find_modules(self)
  226. for module in modules:
  227. if module[0] == "mercurial.pure":
  228. if module[1] != "__init__":
  229. yield ("mercurial", module[1], module[2])
  230. else:
  231. yield module
  232. class hginstallscripts(install_scripts):
  233. '''
  234. This is a specialization of install_scripts that replaces the @LIBDIR@ with
  235. the configured directory for modules. If possible, the path is made relative
  236. to the directory for scripts.
  237. '''
  238. def initialize_options(self):
  239. install_scripts.initialize_options(self)
  240. self.install_lib = None
  241. def finalize_options(self):
  242. install_scripts.finalize_options(self)
  243. self.set_undefined_options('install',
  244. ('install_lib', 'install_lib'))
  245. def run(self):
  246. install_scripts.run(self)
  247. if (os.path.splitdrive(self.install_dir)[0] !=
  248. os.path.splitdrive(self.install_lib)[0]):
  249. # can't make relative paths from one drive to another, so use an
  250. # absolute path instead
  251. libdir = self.install_lib
  252. else:
  253. common = os.path.commonprefix((self.install_dir, self.install_lib))
  254. rest = self.install_dir[len(common):]
  255. uplevel = len([n for n in os.path.split(rest) if n])
  256. libdir = uplevel * ('..' + os.sep) + self.install_lib[len(common):]
  257. for outfile in self.outfiles:
  258. data = open(outfile, 'rb').read()
  259. # skip binary files
  260. if '\0' in data:
  261. continue
  262. data = data.replace('@LIBDIR@', libdir.encode('string_escape'))
  263. open(outfile, 'wb').write(data)
  264. cmdclass = {'build_mo': hgbuildmo,
  265. 'build_ext': hgbuildext,
  266. 'build_py': hgbuildpy,
  267. 'install_scripts': hginstallscripts}
  268. packages = ['mercurial', 'mercurial.hgweb', 'hgext', 'hgext.convert',
  269. 'hgext.highlight', 'hgext.zeroconf']
  270. pymodules = []
  271. extmodules = [
  272. Extension('mercurial.base85', ['mercurial/base85.c']),
  273. Extension('mercurial.bdiff', ['mercurial/bdiff.c']),
  274. Extension('mercurial.diffhelpers', ['mercurial/diffhelpers.c']),
  275. Extension('mercurial.mpatch', ['mercurial/mpatch.c']),
  276. Extension('mercurial.parsers', ['mercurial/parsers.c']),
  277. ]
  278. # disable osutil.c under windows + python 2.4 (issue1364)
  279. if sys.platform == 'win32' and sys.version_info < (2, 5, 0, 'final'):
  280. pymodules.append('mercurial.pure.osutil')
  281. else:
  282. extmodules.append(Extension('mercurial.osutil', ['mercurial/osutil.c']))
  283. if sys.platform == 'linux2' and os.uname()[2] > '2.6':
  284. # The inotify extension is only usable with Linux 2.6 kernels.
  285. # You also need a reasonably recent C library.
  286. # In any case, if it fails to build the error will be skipped ('optional').
  287. cc = new_compiler()
  288. if hasfunction(cc, 'inotify_add_watch'):
  289. inotify = Extension('hgext.inotify.linux._inotify',
  290. ['hgext/inotify/linux/_inotify.c'],
  291. ['mercurial'])
  292. inotify.optional = True
  293. extmodules.append(inotify)
  294. packages.extend(['hgext.inotify', 'hgext.inotify.linux'])
  295. packagedata = {'mercurial': ['locale/*/LC_MESSAGES/hg.mo',
  296. 'help/*.txt']}
  297. def ordinarypath(p):
  298. return p and p[0] != '.' and p[-1] != '~'
  299. for root in ('templates',):
  300. for curdir, dirs, files in os.walk(os.path.join('mercurial', root)):
  301. curdir = curdir.split(os.sep, 1)[1]
  302. dirs[:] = filter(ordinarypath, dirs)
  303. for f in filter(ordinarypath, files):
  304. f = os.path.join(curdir, f)
  305. packagedata['mercurial'].append(f)
  306. datafiles = []
  307. setupversion = version
  308. extra = {}
  309. if py2exeloaded:
  310. extra['console'] = [
  311. {'script':'hg',
  312. 'copyright':'Copyright (C) 2005-2010 Matt Mackall and others',
  313. 'product_version':version}]
  314. if os.name == 'nt':
  315. # Windows binary file versions for exe/dll files must have the
  316. # form W.X.Y.Z, where W,X,Y,Z are numbers in the range 0..65535
  317. setupversion = version.split('+', 1)[0]
  318. setup(name='mercurial',
  319. version=setupversion,
  320. author='Matt Mackall',
  321. author_email='mpm@selenic.com',
  322. url='http://mercurial.selenic.com/',
  323. description='Scalable distributed SCM',
  324. license='GNU GPLv2+',
  325. scripts=scripts,
  326. packages=packages,
  327. py_modules=pymodules,
  328. ext_modules=extmodules,
  329. data_files=datafiles,
  330. package_data=packagedata,
  331. cmdclass=cmdclass,
  332. options=dict(py2exe=dict(packages=['hgext', 'email']),
  333. bdist_mpkg=dict(zipdist=True,
  334. license='COPYING',
  335. readme='contrib/macosx/Readme.html',
  336. welcome='contrib/macosx/Welcome.html')),
  337. **extra)