PageRenderTime 64ms CodeModel.GetById 39ms RepoModel.GetById 1ms app.codeStats 0ms

/mercurial/extensions.py

https://bitbucket.org/mirror/mercurial/
Python | 382 lines | 336 code | 20 blank | 26 comment | 66 complexity | d8dc8ae73a17f4ded3245094f73e579d MD5 | raw file
Possible License(s): GPL-2.0
  1. # extensions.py - extension handling for mercurial
  2. #
  3. # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
  4. #
  5. # This software may be used and distributed according to the terms of the
  6. # GNU General Public License version 2 or any later version.
  7. import imp, os
  8. import util, cmdutil, error
  9. from i18n import _, gettext
  10. _extensions = {}
  11. _order = []
  12. _ignore = ['hbisect', 'bookmarks', 'parentrevspec', 'interhg', 'inotify']
  13. def extensions(ui=None):
  14. if ui:
  15. def enabled(name):
  16. for format in ['%s', 'hgext.%s']:
  17. conf = ui.config('extensions', format % name)
  18. if conf is not None and not conf.startswith('!'):
  19. return True
  20. else:
  21. enabled = lambda name: True
  22. for name in _order:
  23. module = _extensions[name]
  24. if module and enabled(name):
  25. yield name, module
  26. def find(name):
  27. '''return module with given extension name'''
  28. mod = None
  29. try:
  30. mod = _extensions[name]
  31. except KeyError:
  32. for k, v in _extensions.iteritems():
  33. if k.endswith('.' + name) or k.endswith('/' + name):
  34. mod = v
  35. break
  36. if not mod:
  37. raise KeyError(name)
  38. return mod
  39. def loadpath(path, module_name):
  40. module_name = module_name.replace('.', '_')
  41. path = util.normpath(util.expandpath(path))
  42. if os.path.isdir(path):
  43. # module/__init__.py style
  44. d, f = os.path.split(path)
  45. fd, fpath, desc = imp.find_module(f, [d])
  46. return imp.load_module(module_name, fd, fpath, desc)
  47. else:
  48. try:
  49. return imp.load_source(module_name, path)
  50. except IOError, exc:
  51. if not exc.filename:
  52. exc.filename = path # python does not fill this
  53. raise
  54. def load(ui, name, path):
  55. if name.startswith('hgext.') or name.startswith('hgext/'):
  56. shortname = name[6:]
  57. else:
  58. shortname = name
  59. if shortname in _ignore:
  60. return None
  61. if shortname in _extensions:
  62. return _extensions[shortname]
  63. _extensions[shortname] = None
  64. if path:
  65. # the module will be loaded in sys.modules
  66. # choose an unique name so that it doesn't
  67. # conflicts with other modules
  68. mod = loadpath(path, 'hgext.%s' % name)
  69. else:
  70. def importh(name):
  71. mod = __import__(name)
  72. components = name.split('.')
  73. for comp in components[1:]:
  74. mod = getattr(mod, comp)
  75. return mod
  76. try:
  77. mod = importh("hgext.%s" % name)
  78. except ImportError, err:
  79. ui.debug('could not import hgext.%s (%s): trying %s\n'
  80. % (name, err, name))
  81. mod = importh(name)
  82. _extensions[shortname] = mod
  83. _order.append(shortname)
  84. return mod
  85. def loadall(ui):
  86. result = ui.configitems("extensions")
  87. newindex = len(_order)
  88. for (name, path) in result:
  89. if path:
  90. if path[0] == '!':
  91. continue
  92. try:
  93. load(ui, name, path)
  94. except KeyboardInterrupt:
  95. raise
  96. except Exception, inst:
  97. if path:
  98. ui.warn(_("*** failed to import extension %s from %s: %s\n")
  99. % (name, path, inst))
  100. else:
  101. ui.warn(_("*** failed to import extension %s: %s\n")
  102. % (name, inst))
  103. if ui.traceback():
  104. return 1
  105. for name in _order[newindex:]:
  106. uisetup = getattr(_extensions[name], 'uisetup', None)
  107. if uisetup:
  108. uisetup(ui)
  109. for name in _order[newindex:]:
  110. extsetup = getattr(_extensions[name], 'extsetup', None)
  111. if extsetup:
  112. try:
  113. extsetup(ui)
  114. except TypeError:
  115. if extsetup.func_code.co_argcount != 0:
  116. raise
  117. extsetup() # old extsetup with no ui argument
  118. def wrapcommand(table, command, wrapper):
  119. '''Wrap the command named `command' in table
  120. Replace command in the command table with wrapper. The wrapped command will
  121. be inserted into the command table specified by the table argument.
  122. The wrapper will be called like
  123. wrapper(orig, *args, **kwargs)
  124. where orig is the original (wrapped) function, and *args, **kwargs
  125. are the arguments passed to it.
  126. '''
  127. assert callable(wrapper)
  128. aliases, entry = cmdutil.findcmd(command, table)
  129. for alias, e in table.iteritems():
  130. if e is entry:
  131. key = alias
  132. break
  133. origfn = entry[0]
  134. def wrap(*args, **kwargs):
  135. return util.checksignature(wrapper)(
  136. util.checksignature(origfn), *args, **kwargs)
  137. wrap.__doc__ = getattr(origfn, '__doc__')
  138. wrap.__module__ = getattr(origfn, '__module__')
  139. newentry = list(entry)
  140. newentry[0] = wrap
  141. table[key] = tuple(newentry)
  142. return entry
  143. def wrapfunction(container, funcname, wrapper):
  144. '''Wrap the function named funcname in container
  145. Replace the funcname member in the given container with the specified
  146. wrapper. The container is typically a module, class, or instance.
  147. The wrapper will be called like
  148. wrapper(orig, *args, **kwargs)
  149. where orig is the original (wrapped) function, and *args, **kwargs
  150. are the arguments passed to it.
  151. Wrapping methods of the repository object is not recommended since
  152. it conflicts with extensions that extend the repository by
  153. subclassing. All extensions that need to extend methods of
  154. localrepository should use this subclassing trick: namely,
  155. reposetup() should look like
  156. def reposetup(ui, repo):
  157. class myrepo(repo.__class__):
  158. def whatever(self, *args, **kwargs):
  159. [...extension stuff...]
  160. super(myrepo, self).whatever(*args, **kwargs)
  161. [...extension stuff...]
  162. repo.__class__ = myrepo
  163. In general, combining wrapfunction() with subclassing does not
  164. work. Since you cannot control what other extensions are loaded by
  165. your end users, you should play nicely with others by using the
  166. subclass trick.
  167. '''
  168. assert callable(wrapper)
  169. def wrap(*args, **kwargs):
  170. return wrapper(origfn, *args, **kwargs)
  171. origfn = getattr(container, funcname)
  172. assert callable(origfn)
  173. setattr(container, funcname, wrap)
  174. return origfn
  175. def _disabledpaths(strip_init=False):
  176. '''find paths of disabled extensions. returns a dict of {name: path}
  177. removes /__init__.py from packages if strip_init is True'''
  178. import hgext
  179. extpath = os.path.dirname(os.path.abspath(hgext.__file__))
  180. try: # might not be a filesystem path
  181. files = os.listdir(extpath)
  182. except OSError:
  183. return {}
  184. exts = {}
  185. for e in files:
  186. if e.endswith('.py'):
  187. name = e.rsplit('.', 1)[0]
  188. path = os.path.join(extpath, e)
  189. else:
  190. name = e
  191. path = os.path.join(extpath, e, '__init__.py')
  192. if not os.path.exists(path):
  193. continue
  194. if strip_init:
  195. path = os.path.dirname(path)
  196. if name in exts or name in _order or name == '__init__':
  197. continue
  198. exts[name] = path
  199. return exts
  200. def _moduledoc(file):
  201. '''return the top-level python documentation for the given file
  202. Loosely inspired by pydoc.source_synopsis(), but rewritten to
  203. handle triple quotes and to return the whole text instead of just
  204. the synopsis'''
  205. result = []
  206. line = file.readline()
  207. while line[:1] == '#' or not line.strip():
  208. line = file.readline()
  209. if not line:
  210. break
  211. start = line[:3]
  212. if start == '"""' or start == "'''":
  213. line = line[3:]
  214. while line:
  215. if line.rstrip().endswith(start):
  216. line = line.split(start)[0]
  217. if line:
  218. result.append(line)
  219. break
  220. elif not line:
  221. return None # unmatched delimiter
  222. result.append(line)
  223. line = file.readline()
  224. else:
  225. return None
  226. return ''.join(result)
  227. def _disabledhelp(path):
  228. '''retrieve help synopsis of a disabled extension (without importing)'''
  229. try:
  230. file = open(path)
  231. except IOError:
  232. return
  233. else:
  234. doc = _moduledoc(file)
  235. file.close()
  236. if doc: # extracting localized synopsis
  237. return gettext(doc).splitlines()[0]
  238. else:
  239. return _('(no help text available)')
  240. def disabled():
  241. '''find disabled extensions from hgext. returns a dict of {name: desc}'''
  242. try:
  243. from hgext import __index__
  244. return dict((name, gettext(desc))
  245. for name, desc in __index__.docs.iteritems()
  246. if name not in _order)
  247. except (ImportError, AttributeError):
  248. pass
  249. paths = _disabledpaths()
  250. if not paths:
  251. return {}
  252. exts = {}
  253. for name, path in paths.iteritems():
  254. doc = _disabledhelp(path)
  255. if doc:
  256. exts[name] = doc
  257. return exts
  258. def disabledext(name):
  259. '''find a specific disabled extension from hgext. returns desc'''
  260. try:
  261. from hgext import __index__
  262. if name in _order: # enabled
  263. return
  264. else:
  265. return gettext(__index__.docs.get(name))
  266. except (ImportError, AttributeError):
  267. pass
  268. paths = _disabledpaths()
  269. if name in paths:
  270. return _disabledhelp(paths[name])
  271. def disabledcmd(ui, cmd, strict=False):
  272. '''import disabled extensions until cmd is found.
  273. returns (cmdname, extname, module)'''
  274. paths = _disabledpaths(strip_init=True)
  275. if not paths:
  276. raise error.UnknownCommand(cmd)
  277. def findcmd(cmd, name, path):
  278. try:
  279. mod = loadpath(path, 'hgext.%s' % name)
  280. except Exception:
  281. return
  282. try:
  283. aliases, entry = cmdutil.findcmd(cmd,
  284. getattr(mod, 'cmdtable', {}), strict)
  285. except (error.AmbiguousCommand, error.UnknownCommand):
  286. return
  287. except Exception:
  288. ui.warn(_('warning: error finding commands in %s\n') % path)
  289. ui.traceback()
  290. return
  291. for c in aliases:
  292. if c.startswith(cmd):
  293. cmd = c
  294. break
  295. else:
  296. cmd = aliases[0]
  297. return (cmd, name, mod)
  298. ext = None
  299. # first, search for an extension with the same name as the command
  300. path = paths.pop(cmd, None)
  301. if path:
  302. ext = findcmd(cmd, cmd, path)
  303. if not ext:
  304. # otherwise, interrogate each extension until there's a match
  305. for name, path in paths.iteritems():
  306. ext = findcmd(cmd, name, path)
  307. if ext:
  308. break
  309. if ext and 'DEPRECATED' not in ext.__doc__:
  310. return ext
  311. raise error.UnknownCommand(cmd)
  312. def enabled(shortname=True):
  313. '''return a dict of {name: desc} of extensions'''
  314. exts = {}
  315. for ename, ext in extensions():
  316. doc = (gettext(ext.__doc__) or _('(no help text available)'))
  317. if shortname:
  318. ename = ename.split('.')[-1]
  319. exts[ename] = doc.splitlines()[0].strip()
  320. return exts
  321. def moduleversion(module):
  322. '''return version information from given module as a string'''
  323. if (util.safehasattr(module, 'getversion')
  324. and callable(module.getversion)):
  325. version = module.getversion()
  326. elif util.safehasattr(module, '__version__'):
  327. version = module.__version__
  328. else:
  329. version = ''
  330. if isinstance(version, (list, tuple)):
  331. version = '.'.join(str(o) for o in version)
  332. return version