PageRenderTime 52ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/hgext/eol.py

https://bitbucket.org/mirror/mercurial/
Python | 350 lines | 324 code | 2 blank | 24 comment | 8 complexity | 8b4c983c0b4af7fa79717ad42c9d026d MD5 | raw file
Possible License(s): GPL-2.0
  1. """automatically manage newlines in repository files
  2. This extension allows you to manage the type of line endings (CRLF or
  3. LF) that are used in the repository and in the local working
  4. directory. That way you can get CRLF line endings on Windows and LF on
  5. Unix/Mac, thereby letting everybody use their OS native line endings.
  6. The extension reads its configuration from a versioned ``.hgeol``
  7. configuration file found in the root of the working copy. The
  8. ``.hgeol`` file use the same syntax as all other Mercurial
  9. configuration files. It uses two sections, ``[patterns]`` and
  10. ``[repository]``.
  11. The ``[patterns]`` section specifies how line endings should be
  12. converted between the working copy and the repository. The format is
  13. specified by a file pattern. The first match is used, so put more
  14. specific patterns first. The available line endings are ``LF``,
  15. ``CRLF``, and ``BIN``.
  16. Files with the declared format of ``CRLF`` or ``LF`` are always
  17. checked out and stored in the repository in that format and files
  18. declared to be binary (``BIN``) are left unchanged. Additionally,
  19. ``native`` is an alias for checking out in the platform's default line
  20. ending: ``LF`` on Unix (including Mac OS X) and ``CRLF`` on
  21. Windows. Note that ``BIN`` (do nothing to line endings) is Mercurial's
  22. default behaviour; it is only needed if you need to override a later,
  23. more general pattern.
  24. The optional ``[repository]`` section specifies the line endings to
  25. use for files stored in the repository. It has a single setting,
  26. ``native``, which determines the storage line endings for files
  27. declared as ``native`` in the ``[patterns]`` section. It can be set to
  28. ``LF`` or ``CRLF``. The default is ``LF``. For example, this means
  29. that on Windows, files configured as ``native`` (``CRLF`` by default)
  30. will be converted to ``LF`` when stored in the repository. Files
  31. declared as ``LF``, ``CRLF``, or ``BIN`` in the ``[patterns]`` section
  32. are always stored as-is in the repository.
  33. Example versioned ``.hgeol`` file::
  34. [patterns]
  35. **.py = native
  36. **.vcproj = CRLF
  37. **.txt = native
  38. Makefile = LF
  39. **.jpg = BIN
  40. [repository]
  41. native = LF
  42. .. note::
  43. The rules will first apply when files are touched in the working
  44. copy, e.g. by updating to null and back to tip to touch all files.
  45. The extension uses an optional ``[eol]`` section read from both the
  46. normal Mercurial configuration files and the ``.hgeol`` file, with the
  47. latter overriding the former. You can use that section to control the
  48. overall behavior. There are three settings:
  49. - ``eol.native`` (default ``os.linesep``) can be set to ``LF`` or
  50. ``CRLF`` to override the default interpretation of ``native`` for
  51. checkout. This can be used with :hg:`archive` on Unix, say, to
  52. generate an archive where files have line endings for Windows.
  53. - ``eol.only-consistent`` (default True) can be set to False to make
  54. the extension convert files with inconsistent EOLs. Inconsistent
  55. means that there is both ``CRLF`` and ``LF`` present in the file.
  56. Such files are normally not touched under the assumption that they
  57. have mixed EOLs on purpose.
  58. - ``eol.fix-trailing-newline`` (default False) can be set to True to
  59. ensure that converted files end with a EOL character (either ``\\n``
  60. or ``\\r\\n`` as per the configured patterns).
  61. The extension provides ``cleverencode:`` and ``cleverdecode:`` filters
  62. like the deprecated win32text extension does. This means that you can
  63. disable win32text and enable eol and your filters will still work. You
  64. only need to these filters until you have prepared a ``.hgeol`` file.
  65. The ``win32text.forbid*`` hooks provided by the win32text extension
  66. have been unified into a single hook named ``eol.checkheadshook``. The
  67. hook will lookup the expected line endings from the ``.hgeol`` file,
  68. which means you must migrate to a ``.hgeol`` file first before using
  69. the hook. ``eol.checkheadshook`` only checks heads, intermediate
  70. invalid revisions will be pushed. To forbid them completely, use the
  71. ``eol.checkallhook`` hook. These hooks are best used as
  72. ``pretxnchangegroup`` hooks.
  73. See :hg:`help patterns` for more information about the glob patterns
  74. used.
  75. """
  76. from mercurial.i18n import _
  77. from mercurial import util, config, extensions, match, error
  78. import re, os
  79. testedwith = 'internal'
  80. # Matches a lone LF, i.e., one that is not part of CRLF.
  81. singlelf = re.compile('(^|[^\r])\n')
  82. # Matches a single EOL which can either be a CRLF where repeated CR
  83. # are removed or a LF. We do not care about old Macintosh files, so a
  84. # stray CR is an error.
  85. eolre = re.compile('\r*\n')
  86. def inconsistenteol(data):
  87. return '\r\n' in data and singlelf.search(data)
  88. def tolf(s, params, ui, **kwargs):
  89. """Filter to convert to LF EOLs."""
  90. if util.binary(s):
  91. return s
  92. if ui.configbool('eol', 'only-consistent', True) and inconsistenteol(s):
  93. return s
  94. if (ui.configbool('eol', 'fix-trailing-newline', False)
  95. and s and s[-1] != '\n'):
  96. s = s + '\n'
  97. return eolre.sub('\n', s)
  98. def tocrlf(s, params, ui, **kwargs):
  99. """Filter to convert to CRLF EOLs."""
  100. if util.binary(s):
  101. return s
  102. if ui.configbool('eol', 'only-consistent', True) and inconsistenteol(s):
  103. return s
  104. if (ui.configbool('eol', 'fix-trailing-newline', False)
  105. and s and s[-1] != '\n'):
  106. s = s + '\n'
  107. return eolre.sub('\r\n', s)
  108. def isbinary(s, params):
  109. """Filter to do nothing with the file."""
  110. return s
  111. filters = {
  112. 'to-lf': tolf,
  113. 'to-crlf': tocrlf,
  114. 'is-binary': isbinary,
  115. # The following provide backwards compatibility with win32text
  116. 'cleverencode:': tolf,
  117. 'cleverdecode:': tocrlf
  118. }
  119. class eolfile(object):
  120. def __init__(self, ui, root, data):
  121. self._decode = {'LF': 'to-lf', 'CRLF': 'to-crlf', 'BIN': 'is-binary'}
  122. self._encode = {'LF': 'to-lf', 'CRLF': 'to-crlf', 'BIN': 'is-binary'}
  123. self.cfg = config.config()
  124. # Our files should not be touched. The pattern must be
  125. # inserted first override a '** = native' pattern.
  126. self.cfg.set('patterns', '.hg*', 'BIN', 'eol')
  127. # We can then parse the user's patterns.
  128. self.cfg.parse('.hgeol', data)
  129. isrepolf = self.cfg.get('repository', 'native') != 'CRLF'
  130. self._encode['NATIVE'] = isrepolf and 'to-lf' or 'to-crlf'
  131. iswdlf = ui.config('eol', 'native', os.linesep) in ('LF', '\n')
  132. self._decode['NATIVE'] = iswdlf and 'to-lf' or 'to-crlf'
  133. include = []
  134. exclude = []
  135. for pattern, style in self.cfg.items('patterns'):
  136. key = style.upper()
  137. if key == 'BIN':
  138. exclude.append(pattern)
  139. else:
  140. include.append(pattern)
  141. # This will match the files for which we need to care
  142. # about inconsistent newlines.
  143. self.match = match.match(root, '', [], include, exclude)
  144. def copytoui(self, ui):
  145. for pattern, style in self.cfg.items('patterns'):
  146. key = style.upper()
  147. try:
  148. ui.setconfig('decode', pattern, self._decode[key], 'eol')
  149. ui.setconfig('encode', pattern, self._encode[key], 'eol')
  150. except KeyError:
  151. ui.warn(_("ignoring unknown EOL style '%s' from %s\n")
  152. % (style, self.cfg.source('patterns', pattern)))
  153. # eol.only-consistent can be specified in ~/.hgrc or .hgeol
  154. for k, v in self.cfg.items('eol'):
  155. ui.setconfig('eol', k, v, 'eol')
  156. def checkrev(self, repo, ctx, files):
  157. failed = []
  158. for f in (files or ctx.files()):
  159. if f not in ctx:
  160. continue
  161. for pattern, style in self.cfg.items('patterns'):
  162. if not match.match(repo.root, '', [pattern])(f):
  163. continue
  164. target = self._encode[style.upper()]
  165. data = ctx[f].data()
  166. if (target == "to-lf" and "\r\n" in data
  167. or target == "to-crlf" and singlelf.search(data)):
  168. failed.append((str(ctx), target, f))
  169. break
  170. return failed
  171. def parseeol(ui, repo, nodes):
  172. try:
  173. for node in nodes:
  174. try:
  175. if node is None:
  176. # Cannot use workingctx.data() since it would load
  177. # and cache the filters before we configure them.
  178. data = repo.wfile('.hgeol').read()
  179. else:
  180. data = repo[node]['.hgeol'].data()
  181. return eolfile(ui, repo.root, data)
  182. except (IOError, LookupError):
  183. pass
  184. except error.ParseError, inst:
  185. ui.warn(_("warning: ignoring .hgeol file due to parse error "
  186. "at %s: %s\n") % (inst.args[1], inst.args[0]))
  187. return None
  188. def _checkhook(ui, repo, node, headsonly):
  189. # Get revisions to check and touched files at the same time
  190. files = set()
  191. revs = set()
  192. for rev in xrange(repo[node].rev(), len(repo)):
  193. revs.add(rev)
  194. if headsonly:
  195. ctx = repo[rev]
  196. files.update(ctx.files())
  197. for pctx in ctx.parents():
  198. revs.discard(pctx.rev())
  199. failed = []
  200. for rev in revs:
  201. ctx = repo[rev]
  202. eol = parseeol(ui, repo, [ctx.node()])
  203. if eol:
  204. failed.extend(eol.checkrev(repo, ctx, files))
  205. if failed:
  206. eols = {'to-lf': 'CRLF', 'to-crlf': 'LF'}
  207. msgs = []
  208. for node, target, f in failed:
  209. msgs.append(_(" %s in %s should not have %s line endings") %
  210. (f, node, eols[target]))
  211. raise util.Abort(_("end-of-line check failed:\n") + "\n".join(msgs))
  212. def checkallhook(ui, repo, node, hooktype, **kwargs):
  213. """verify that files have expected EOLs"""
  214. _checkhook(ui, repo, node, False)
  215. def checkheadshook(ui, repo, node, hooktype, **kwargs):
  216. """verify that files have expected EOLs"""
  217. _checkhook(ui, repo, node, True)
  218. # "checkheadshook" used to be called "hook"
  219. hook = checkheadshook
  220. def preupdate(ui, repo, hooktype, parent1, parent2):
  221. repo.loadeol([parent1])
  222. return False
  223. def uisetup(ui):
  224. ui.setconfig('hooks', 'preupdate.eol', preupdate, 'eol')
  225. def extsetup(ui):
  226. try:
  227. extensions.find('win32text')
  228. ui.warn(_("the eol extension is incompatible with the "
  229. "win32text extension\n"))
  230. except KeyError:
  231. pass
  232. def reposetup(ui, repo):
  233. uisetup(repo.ui)
  234. if not repo.local():
  235. return
  236. for name, fn in filters.iteritems():
  237. repo.adddatafilter(name, fn)
  238. ui.setconfig('patch', 'eol', 'auto', 'eol')
  239. class eolrepo(repo.__class__):
  240. def loadeol(self, nodes):
  241. eol = parseeol(self.ui, self, nodes)
  242. if eol is None:
  243. return None
  244. eol.copytoui(self.ui)
  245. return eol.match
  246. def _hgcleardirstate(self):
  247. self._eolfile = self.loadeol([None, 'tip'])
  248. if not self._eolfile:
  249. self._eolfile = util.never
  250. return
  251. try:
  252. cachemtime = os.path.getmtime(self.join("eol.cache"))
  253. except OSError:
  254. cachemtime = 0
  255. try:
  256. eolmtime = os.path.getmtime(self.wjoin(".hgeol"))
  257. except OSError:
  258. eolmtime = 0
  259. if eolmtime > cachemtime:
  260. self.ui.debug("eol: detected change in .hgeol\n")
  261. wlock = None
  262. try:
  263. wlock = self.wlock()
  264. for f in self.dirstate:
  265. if self.dirstate[f] == 'n':
  266. # all normal files need to be looked at
  267. # again since the new .hgeol file might no
  268. # longer match a file it matched before
  269. self.dirstate.normallookup(f)
  270. # Create or touch the cache to update mtime
  271. self.opener("eol.cache", "w").close()
  272. wlock.release()
  273. except error.LockUnavailable:
  274. # If we cannot lock the repository and clear the
  275. # dirstate, then a commit might not see all files
  276. # as modified. But if we cannot lock the
  277. # repository, then we can also not make a commit,
  278. # so ignore the error.
  279. pass
  280. def commitctx(self, ctx, error=False):
  281. for f in sorted(ctx.added() + ctx.modified()):
  282. if not self._eolfile(f):
  283. continue
  284. try:
  285. data = ctx[f].data()
  286. except IOError:
  287. continue
  288. if util.binary(data):
  289. # We should not abort here, since the user should
  290. # be able to say "** = native" to automatically
  291. # have all non-binary files taken care of.
  292. continue
  293. if inconsistenteol(data):
  294. raise util.Abort(_("inconsistent newline style "
  295. "in %s\n") % f)
  296. return super(eolrepo, self).commitctx(ctx, error)
  297. repo.__class__ = eolrepo
  298. repo._hgcleardirstate()