build.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. #!/usr/bin/env python
  2. # Copyright (c) 2002-2005 ActiveState
  3. # See LICENSE.txt for license details.
  4. """
  5. which.py dev build script
  6. Usage:
  7. python build.py [<options>...] [<targets>...]
  8. Options:
  9. --help, -h Print this help and exit.
  10. --targets, -t List all available targets.
  11. This is the primary build script for the which.py project. It exists
  12. to assist in building, maintaining, and distributing this project.
  13. It is intended to have Makefile semantics. I.e. 'python build.py'
  14. will build execute the default target, 'python build.py foo' will
  15. build target foo, etc. However, there is no intelligent target
  16. interdependency tracking (I suppose I could do that with function
  17. attributes).
  18. """
  19. import os
  20. from os.path import basename, dirname, splitext, isfile, isdir, exists, \
  21. join, abspath, normpath
  22. import sys
  23. import getopt
  24. import types
  25. import getpass
  26. import shutil
  27. import glob
  28. import logging
  29. import re
  30. #---- exceptions
  31. class Error(Exception):
  32. pass
  33. #---- globals
  34. log = logging.getLogger("build")
  35. #---- globals
  36. _project_name_ = "which"
  37. #---- internal support routines
  38. def _get_trentm_com_dir():
  39. """Return the path to the local trentm.com source tree."""
  40. d = normpath(join(dirname(__file__), os.pardir, "trentm.com"))
  41. if not isdir(d):
  42. raise Error("could not find 'trentm.com' src dir at '%s'" % d)
  43. return d
  44. def _get_local_bits_dir():
  45. import imp
  46. info = imp.find_module("tmconfig", [_get_trentm_com_dir()])
  47. tmconfig = imp.load_module("tmconfig", *info)
  48. return tmconfig.bitsDir
  49. def _get_project_bits_dir():
  50. d = normpath(join(dirname(__file__), "bits"))
  51. return d
  52. def _get_project_version():
  53. import imp, os
  54. data = imp.find_module(_project_name_, [os.path.dirname(__file__)])
  55. mod = imp.load_module(_project_name_, *data)
  56. return mod.__version__
  57. # Recipe: run (0.5.1) in /Users/trentm/tm/recipes/cookbook
  58. _RUN_DEFAULT_LOGSTREAM = ("RUN", "DEFAULT", "LOGSTREAM")
  59. def __run_log(logstream, msg, *args, **kwargs):
  60. if not logstream:
  61. pass
  62. elif logstream is _RUN_DEFAULT_LOGSTREAM:
  63. try:
  64. log.debug(msg, *args, **kwargs)
  65. except NameError:
  66. pass
  67. else:
  68. logstream(msg, *args, **kwargs)
  69. def _run(cmd, logstream=_RUN_DEFAULT_LOGSTREAM):
  70. """Run the given command.
  71. "cmd" is the command to run
  72. "logstream" is an optional logging stream on which to log the command.
  73. If None, no logging is done. If unspecifed, this looks for a Logger
  74. instance named 'log' and logs the command on log.debug().
  75. Raises OSError is the command returns a non-zero exit status.
  76. """
  77. __run_log(logstream, "running '%s'", cmd)
  78. retval = os.system(cmd)
  79. if hasattr(os, "WEXITSTATUS"):
  80. status = os.WEXITSTATUS(retval)
  81. else:
  82. status = retval
  83. if status:
  84. #TODO: add std OSError attributes or pick more approp. exception
  85. raise OSError("error running '%s': %r" % (cmd, status))
  86. def _run_in_dir(cmd, cwd, logstream=_RUN_DEFAULT_LOGSTREAM):
  87. old_dir = os.getcwd()
  88. try:
  89. os.chdir(cwd)
  90. __run_log(logstream, "running '%s' in '%s'", cmd, cwd)
  91. _run(cmd, logstream=None)
  92. finally:
  93. os.chdir(old_dir)
  94. # Recipe: rmtree (0.5) in /Users/trentm/tm/recipes/cookbook
  95. def _rmtree_OnError(rmFunction, filePath, excInfo):
  96. if excInfo[0] == OSError:
  97. # presuming because file is read-only
  98. os.chmod(filePath, 0777)
  99. rmFunction(filePath)
  100. def _rmtree(dirname):
  101. import shutil
  102. shutil.rmtree(dirname, 0, _rmtree_OnError)
  103. # Recipe: pretty_logging (0.1) in /Users/trentm/tm/recipes/cookbook
  104. class _PerLevelFormatter(logging.Formatter):
  105. """Allow multiple format string -- depending on the log level.
  106. A "fmtFromLevel" optional arg is added to the constructor. It can be
  107. a dictionary mapping a log record level to a format string. The
  108. usual "fmt" argument acts as the default.
  109. """
  110. def __init__(self, fmt=None, datefmt=None, fmtFromLevel=None):
  111. logging.Formatter.__init__(self, fmt, datefmt)
  112. if fmtFromLevel is None:
  113. self.fmtFromLevel = {}
  114. else:
  115. self.fmtFromLevel = fmtFromLevel
  116. def format(self, record):
  117. record.levelname = record.levelname.lower()
  118. if record.levelno in self.fmtFromLevel:
  119. #XXX This is a non-threadsafe HACK. Really the base Formatter
  120. # class should provide a hook accessor for the _fmt
  121. # attribute. *Could* add a lock guard here (overkill?).
  122. _saved_fmt = self._fmt
  123. self._fmt = self.fmtFromLevel[record.levelno]
  124. try:
  125. return logging.Formatter.format(self, record)
  126. finally:
  127. self._fmt = _saved_fmt
  128. else:
  129. return logging.Formatter.format(self, record)
  130. def _setup_logging():
  131. hdlr = logging.StreamHandler()
  132. defaultFmt = "%(name)s: %(levelname)s: %(message)s"
  133. infoFmt = "%(name)s: %(message)s"
  134. fmtr = _PerLevelFormatter(fmt=defaultFmt,
  135. fmtFromLevel={logging.INFO: infoFmt})
  136. hdlr.setFormatter(fmtr)
  137. logging.root.addHandler(hdlr)
  138. log.setLevel(logging.INFO)
  139. def _getTargets():
  140. """Find all targets and return a dict of targetName:targetFunc items."""
  141. targets = {}
  142. for name, attr in sys.modules[__name__].__dict__.items():
  143. if name.startswith('target_'):
  144. targets[ name[len('target_'):] ] = attr
  145. return targets
  146. def _listTargets(targets):
  147. """Pretty print a list of targets."""
  148. width = 77
  149. nameWidth = 15 # min width
  150. for name in targets.keys():
  151. nameWidth = max(nameWidth, len(name))
  152. nameWidth += 2 # space btwn name and doc
  153. format = "%%-%ds%%s" % nameWidth
  154. print format % ("TARGET", "DESCRIPTION")
  155. for name, func in sorted(targets.items()):
  156. doc = _first_paragraph(func.__doc__ or "", True)
  157. if len(doc) > (width - nameWidth):
  158. doc = doc[:(width-nameWidth-3)] + "..."
  159. print format % (name, doc)
  160. # Recipe: first_paragraph (1.0.1) in /Users/trentm/tm/recipes/cookbook
  161. def _first_paragraph(text, join_lines=False):
  162. """Return the first paragraph of the given text."""
  163. para = text.lstrip().split('\n\n', 1)[0]
  164. if join_lines:
  165. lines = [line.strip() for line in para.splitlines(0)]
  166. para = ' '.join(lines)
  167. return para
  168. #---- build targets
  169. def target_default():
  170. target_all()
  171. def target_all():
  172. """Build all release packages."""
  173. log.info("target: default")
  174. if sys.platform == "win32":
  175. target_launcher()
  176. target_sdist()
  177. target_webdist()
  178. def target_clean():
  179. """remove all build/generated bits"""
  180. log.info("target: clean")
  181. if sys.platform == "win32":
  182. _run("nmake -f Makefile.win clean")
  183. ver = _get_project_version()
  184. dirs = ["dist", "build", "%s-%s" % (_project_name_, ver)]
  185. for d in dirs:
  186. print "removing '%s'" % d
  187. if os.path.isdir(d): _rmtree(d)
  188. patterns = ["*.pyc", "*~", "MANIFEST",
  189. os.path.join("test", "*~"),
  190. os.path.join("test", "*.pyc"),
  191. ]
  192. for pattern in patterns:
  193. for file in glob.glob(pattern):
  194. print "removing '%s'" % file
  195. os.unlink(file)
  196. def target_launcher():
  197. """Build the Windows launcher executable."""
  198. log.info("target: launcher")
  199. assert sys.platform == "win32", "'launcher' target only supported on Windows"
  200. _run("nmake -f Makefile.win")
  201. def target_docs():
  202. """Regenerate some doc bits from project-info.xml."""
  203. log.info("target: docs")
  204. _run("projinfo -f project-info.xml -R -o README.txt --force")
  205. _run("projinfo -f project-info.xml --index-markdown -o index.markdown --force")
  206. def target_sdist():
  207. """Build a source distribution."""
  208. log.info("target: sdist")
  209. target_docs()
  210. bitsDir = _get_project_bits_dir()
  211. _run("python setup.py sdist -f --formats zip -d %s" % bitsDir,
  212. log.info)
  213. def target_webdist():
  214. """Build a web dist package.
  215. "Web dist" packages are zip files with '.web' package. All files in
  216. the zip must be under a dir named after the project. There must be a
  217. webinfo.xml file at <projname>/webinfo.xml. This file is "defined"
  218. by the parsing in trentm.com/build.py.
  219. """
  220. assert sys.platform != "win32", "'webdist' not implemented for win32"
  221. log.info("target: webdist")
  222. bitsDir = _get_project_bits_dir()
  223. buildDir = join("build", "webdist")
  224. distDir = join(buildDir, _project_name_)
  225. if exists(buildDir):
  226. _rmtree(buildDir)
  227. os.makedirs(distDir)
  228. target_docs()
  229. # Copy the webdist bits to the build tree.
  230. manifest = [
  231. "project-info.xml",
  232. "index.markdown",
  233. "LICENSE.txt",
  234. "which.py",
  235. "logo.jpg",
  236. ]
  237. for src in manifest:
  238. if dirname(src):
  239. dst = join(distDir, dirname(src))
  240. os.makedirs(dst)
  241. else:
  242. dst = distDir
  243. _run("cp %s %s" % (src, dst))
  244. # Zip up the webdist contents.
  245. ver = _get_project_version()
  246. bit = abspath(join(bitsDir, "%s-%s.web" % (_project_name_, ver)))
  247. if exists(bit):
  248. os.remove(bit)
  249. _run_in_dir("zip -r %s %s" % (bit, _project_name_), buildDir, log.info)
  250. def target_install():
  251. """Use the setup.py script to install."""
  252. log.info("target: install")
  253. _run("python setup.py install")
  254. def target_upload_local():
  255. """Update release bits to *local* trentm.com bits-dir location.
  256. This is different from the "upload" target, which uploads release
  257. bits remotely to trentm.com.
  258. """
  259. log.info("target: upload_local")
  260. assert sys.platform != "win32", "'upload_local' not implemented for win32"
  261. ver = _get_project_version()
  262. localBitsDir = _get_local_bits_dir()
  263. uploadDir = join(localBitsDir, _project_name_, ver)
  264. bitsPattern = join(_get_project_bits_dir(),
  265. "%s-*%s*" % (_project_name_, ver))
  266. bits = glob.glob(bitsPattern)
  267. if not bits:
  268. log.info("no bits matching '%s' to upload", bitsPattern)
  269. else:
  270. if not exists(uploadDir):
  271. os.makedirs(uploadDir)
  272. for bit in bits:
  273. _run("cp %s %s" % (bit, uploadDir), log.info)
  274. def target_upload():
  275. """Upload binary and source distribution to trentm.com bits
  276. directory.
  277. """
  278. log.info("target: upload")
  279. ver = _get_project_version()
  280. bitsDir = _get_project_bits_dir()
  281. bitsPattern = join(bitsDir, "%s-*%s*" % (_project_name_, ver))
  282. bits = glob.glob(bitsPattern)
  283. if not bits:
  284. log.info("no bits matching '%s' to upload", bitsPattern)
  285. return
  286. # Ensure have all the expected bits.
  287. expectedBits = [
  288. re.compile("%s-.*\.zip$" % _project_name_),
  289. re.compile("%s-.*\.web$" % _project_name_)
  290. ]
  291. for expectedBit in expectedBits:
  292. for bit in bits:
  293. if expectedBit.search(bit):
  294. break
  295. else:
  296. raise Error("can't find expected bit matching '%s' in '%s' dir"
  297. % (expectedBit.pattern, bitsDir))
  298. # Upload the bits.
  299. user = "trentm"
  300. host = "trentm.com"
  301. remoteBitsBaseDir = "~/data/bits"
  302. remoteBitsDir = join(remoteBitsBaseDir, _project_name_, ver)
  303. if sys.platform == "win32":
  304. ssh = "plink"
  305. scp = "pscp -unsafe"
  306. else:
  307. ssh = "ssh"
  308. scp = "scp"
  309. _run("%s %s@%s 'mkdir -p %s'" % (ssh, user, host, remoteBitsDir), log.info)
  310. for bit in bits:
  311. _run("%s %s %s@%s:%s" % (scp, bit, user, host, remoteBitsDir),
  312. log.info)
  313. def target_check_version():
  314. """grep for version strings in source code
  315. List all things that look like version strings in the source code.
  316. Used for checking that versioning is updated across the board.
  317. """
  318. sources = [
  319. "which.py",
  320. "project-info.xml",
  321. ]
  322. pattern = r'[0-9]\+\(\.\|, \)[0-9]\+\(\.\|, \)[0-9]\+'
  323. _run('grep -n "%s" %s' % (pattern, ' '.join(sources)), None)
  324. #---- mainline
  325. def build(targets=[]):
  326. log.debug("build(targets=%r)" % targets)
  327. available = _getTargets()
  328. if not targets:
  329. if available.has_key('default'):
  330. return available['default']()
  331. else:
  332. log.warn("No default target available. Doing nothing.")
  333. else:
  334. for target in targets:
  335. if available.has_key(target):
  336. retval = available[target]()
  337. if retval:
  338. raise Error("Error running '%s' target: retval=%s"\
  339. % (target, retval))
  340. else:
  341. raise Error("Unknown target: '%s'" % target)
  342. def main(argv):
  343. _setup_logging()
  344. # Process options.
  345. optlist, targets = getopt.getopt(argv[1:], 'ht', ['help', 'targets'])
  346. for opt, optarg in optlist:
  347. if opt in ('-h', '--help'):
  348. sys.stdout.write(__doc__ + '\n')
  349. return 0
  350. elif opt in ('-t', '--targets'):
  351. return _listTargets(_getTargets())
  352. return build(targets)
  353. if __name__ == "__main__":
  354. sys.exit( main(sys.argv) )