Debian Codegraph @

hgext/eol.py

raw
1 """automatically manage newlines in repository files
2
3 This extension allows you to manage the type of line endings (CRLF or
4 LF) that are used in the repository and in the local working
5 directory. That way you can get CRLF line endings on Windows and LF on
6 Unix/Mac, thereby letting everybody use their OS native line endings.
7
8 The extension reads its configuration from a versioned ``.hgeol``
9 configuration file found in the root of the working directory. The
10 ``.hgeol`` file use the same syntax as all other Mercurial
11 configuration files. It uses two sections, ``[patterns]`` and
12 ``[repository]``.
13
14 The ``[patterns]`` section specifies how line endings should be
15 converted between the working directory and the repository. The format is
16 specified by a file pattern. The first match is used, so put more
17 specific patterns first. The available line endings are ``LF``,
18 ``CRLF``, and ``BIN``.
19
20 Files with the declared format of ``CRLF`` or ``LF`` are always
21 checked out and stored in the repository in that format and files
22 declared to be binary (``BIN``) are left unchanged. Additionally,
23 ``native`` is an alias for checking out in the platform's default line
24 ending: ``LF`` on Unix (including Mac OS X) and ``CRLF`` on
25 Windows. Note that ``BIN`` (do nothing to line endings) is Mercurial's
26 default behavior; it is only needed if you need to override a later,
27 more general pattern.
28
29 The optional ``[repository]`` section specifies the line endings to
30 use for files stored in the repository. It has a single setting,
31 ``native``, which determines the storage line endings for files
32 declared as ``native`` in the ``[patterns]`` section. It can be set to
33 ``LF`` or ``CRLF``. The default is ``LF``. For example, this means
34 that on Windows, files configured as ``native`` (``CRLF`` by default)
35 will be converted to ``LF`` when stored in the repository. Files
36 declared as ``LF``, ``CRLF``, or ``BIN`` in the ``[patterns]`` section
37 are always stored as-is in the repository.
38
39 Example versioned ``.hgeol`` file::
40
41 [patterns]
42 **.py = native
43 **.vcproj = CRLF
44 **.txt = native
45 Makefile = LF
46 **.jpg = BIN
47
48 [repository]
49 native = LF
50
51 .. note::
52
53 The rules will first apply when files are touched in the working
54 directory, e.g. by updating to null and back to tip to touch all files.
55
56 The extension uses an optional ``[eol]`` section read from both the
57 normal Mercurial configuration files and the ``.hgeol`` file, with the
58 latter overriding the former. You can use that section to control the
59 overall behavior. There are three settings:
60
61 - ``eol.native`` (default ``os.linesep``) can be set to ``LF`` or
62 ``CRLF`` to override the default interpretation of ``native`` for
63 checkout. This can be used with :hg:`archive` on Unix, say, to
64 generate an archive where files have line endings for Windows.
65
66 - ``eol.only-consistent`` (default True) can be set to False to make
67 the extension convert files with inconsistent EOLs. Inconsistent
68 means that there is both ``CRLF`` and ``LF`` present in the file.
69 Such files are normally not touched under the assumption that they
70 have mixed EOLs on purpose.
71
72 - ``eol.fix-trailing-newline`` (default False) can be set to True to
73 ensure that converted files end with a EOL character (either ``\\n``
74 or ``\\r\\n`` as per the configured patterns).
75
76 The extension provides ``cleverencode:`` and ``cleverdecode:`` filters
77 like the deprecated win32text extension does. This means that you can
78 disable win32text and enable eol and your filters will still work. You
79 only need to these filters until you have prepared a ``.hgeol`` file.
80
81 The ``win32text.forbid*`` hooks provided by the win32text extension
82 have been unified into a single hook named ``eol.checkheadshook``. The
83 hook will lookup the expected line endings from the ``.hgeol`` file,
84 which means you must migrate to a ``.hgeol`` file first before using
85 the hook. ``eol.checkheadshook`` only checks heads, intermediate
86 invalid revisions will be pushed. To forbid them completely, use the
87 ``eol.checkallhook`` hook. These hooks are best used as
88 ``pretxnchangegroup`` hooks.
89
90 See :hg:`help patterns` for more information about the glob patterns
91 used.
92 """
93
94 from __future__ import annotations
95
96 import os
97 import re
98 from mercurial.i18n import _
99 from mercurial import (
100 config,
101 error as errormod,
102 extensions,
103 match,
104 merge,
105 pycompat,
106 registrar,
107 scmutil,
108 util,
109 )
110 from mercurial.utils import stringutil
111
112 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
113 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
114 # be specifying the version(s) of Mercurial they are tested with, or
115 # leave the attribute unspecified.
116 testedwith = b'ships-with-hg-core'
117
118 configtable = {}
119 configitem = registrar.configitem(configtable)
120
121 configitem(
122 b'eol',
123 b'fix-trailing-newline',
124 default=False,
125 )
126 configitem(
127 b'eol',
128 b'native',
129 default=pycompat.oslinesep,
130 )
131 configitem(
132 b'eol',
133 b'only-consistent',
134 default=True,
135 )
136
137 # Matches a lone LF, i.e., one that is not part of CRLF.
138 singlelf = re.compile(b'(^|[^\r])\n')
139
140
141 def inconsistenteol(data):
142 return b'\r\n' in data and singlelf.search(data)
143
144
145 def tolf(s, params, ui, **kwargs):
146 """Filter to convert to LF EOLs."""
147 if stringutil.binary(s):
148 return s
149 if ui.configbool(b'eol', b'only-consistent') and inconsistenteol(s):
150 return s
151 if (
152 ui.configbool(b'eol', b'fix-trailing-newline')
153 and s
154 and not s.endswith(b'\n')
155 ):
156 s = s + b'\n'
157 return util.tolf(s)
158
159
160 def tocrlf(s, params, ui, **kwargs):
161 """Filter to convert to CRLF EOLs."""
162 if stringutil.binary(s):
163 return s
164 if ui.configbool(b'eol', b'only-consistent') and inconsistenteol(s):
165 return s
166 if (
167 ui.configbool(b'eol', b'fix-trailing-newline')
168 and s
169 and not s.endswith(b'\n')
170 ):
171 s = s + b'\n'
172 return util.tocrlf(s)
173
174
175 def isbinary(s, params, ui, **kwargs):
176 """Filter to do nothing with the file."""
177 return s
178
179
180 filters = {
181 b'to-lf': tolf,
182 b'to-crlf': tocrlf,
183 b'is-binary': isbinary,
184 # The following provide backwards compatibility with win32text
185 b'cleverencode:': tolf,
186 b'cleverdecode:': tocrlf,
187 }
188
189
190 class eolfile:
191 def __init__(self, ui, root, data):
192 self._decode = {
193 b'LF': b'to-lf',
194 b'CRLF': b'to-crlf',
195 b'BIN': b'is-binary',
196 }
197 self._encode = {
198 b'LF': b'to-lf',
199 b'CRLF': b'to-crlf',
200 b'BIN': b'is-binary',
201 }
202
203 self.cfg = config.config()
204 # Our files should not be touched. The pattern must be
205 # inserted first override a '** = native' pattern.
206 self.cfg.set(b'patterns', b'.hg*', b'BIN', b'eol')
207 # We can then parse the user's patterns.
208 self.cfg.parse(b'.hgeol', data)
209
210 isrepolf = self.cfg.get(b'repository', b'native') != b'CRLF'
211 self._encode[b'NATIVE'] = isrepolf and b'to-lf' or b'to-crlf'
212 iswdlf = ui.config(b'eol', b'native') in (b'LF', b'\n')
213 self._decode[b'NATIVE'] = iswdlf and b'to-lf' or b'to-crlf'
214
215 include = []
216 exclude = []
217 self.patterns = []
218 for pattern, style in self.cfg.items(b'patterns'):
219 key = style.upper()
220 if key == b'BIN':
221 exclude.append(pattern)
222 else:
223 include.append(pattern)
224 m = match.match(root, b'', [pattern])
225 self.patterns.append((pattern, key, m))
226 # This will match the files for which we need to care
227 # about inconsistent newlines.
228 self.match = match.match(root, b'', [], include, exclude)
229
230 def copytoui(self, ui):
231 newpatterns = {pattern for pattern, key, m in self.patterns}
232 for section in (b'decode', b'encode'):
233 for oldpattern, _filter in ui.configitems(section):
234 if oldpattern not in newpatterns:
235 if ui.configsource(section, oldpattern) == b'eol':
236 ui.setconfig(section, oldpattern, b'!', b'eol')
237 for pattern, key, m in self.patterns:
238 try:
239 ui.setconfig(b'decode', pattern, self._decode[key], b'eol')
240 ui.setconfig(b'encode', pattern, self._encode[key], b'eol')
241 except KeyError:
242 ui.warn(
243 _(b"ignoring unknown EOL style '%s' from %s\n")
244 % (key, self.cfg.source(b'patterns', pattern))
245 )
246 # eol.only-consistent can be specified in ~/.hgrc or .hgeol
247 for k, v in self.cfg.items(b'eol'):
248 ui.setconfig(b'eol', k, v, b'eol')
249
250 def checkrev(self, repo, ctx, files):
251 failed = []
252 for f in files or ctx.files():
253 if f not in ctx:
254 continue
255 for pattern, key, m in self.patterns:
256 if not m(f):
257 continue
258 target = self._encode[key]
259 data = ctx[f].data()
260 if (
261 target == b"to-lf"
262 and b"\r\n" in data
263 or target == b"to-crlf"
264 and singlelf.search(data)
265 ):
266 failed.append((f, target, bytes(ctx)))
267 break
268 return failed
269
270
271 def parseeol(ui, repo, nodes):
272 try:
273 for node in nodes:
274 try:
275 if node is None:
276 # Cannot use workingctx.data() since it would load
277 # and cache the filters before we configure them.
278 data = repo.wvfs(b'.hgeol').read()
279 else:
280 data = repo[node][b'.hgeol'].data()
281 return eolfile(ui, repo.root, data)
282 except (OSError, LookupError):
283 pass
284 except errormod.ConfigError as inst:
285 ui.warn(
286 _(
287 b"warning: ignoring .hgeol file due to parse error "
288 b"at %s: %s\n"
289 )
290 % (inst.location, inst.message)
291 )
292 return None
293
294
295 def ensureenabled(ui):
296 """make sure the extension is enabled when used as hook
297
298 When eol is used through hooks, the extension is never formally loaded and
299 enabled. This has some side effect, for example the config declaration is
300 never loaded. This function ensure the extension is enabled when running
301 hooks.
302 """
303 if b'eol' in ui._knownconfig:
304 return
305 ui.setconfig(b'extensions', b'eol', b'', source=b'internal')
306 extensions.loadall(ui, [b'eol'])
307
308
309 def _checkhook(ui, repo, node, headsonly):
310 # Get revisions to check and touched files at the same time
311 ensureenabled(ui)
312 files = set()
313 revs = set()
314 for rev in range(repo[node].rev(), len(repo)):
315 revs.add(rev)
316 if headsonly:
317 ctx = repo[rev]
318 files.update(ctx.files())
319 for pctx in ctx.parents():
320 revs.discard(pctx.rev())
321 failed = []
322 for rev in revs:
323 ctx = repo[rev]
324 eol = parseeol(ui, repo, [ctx.node()])
325 if eol:
326 failed.extend(eol.checkrev(repo, ctx, files))
327
328 if failed:
329 eols = {b'to-lf': b'CRLF', b'to-crlf': b'LF'}
330 msgs = []
331 for f, target, node in sorted(failed):
332 msgs.append(
333 _(b" %s in %s should not have %s line endings")
334 % (f, node, eols[target])
335 )
336 raise errormod.Abort(
337 _(b"end-of-line check failed:\n") + b"\n".join(msgs)
338 )
339
340
341 def checkallhook(ui, repo, node, hooktype, **kwargs):
342 """verify that files have expected EOLs"""
343 _checkhook(ui, repo, node, False)
344
345
346 def checkheadshook(ui, repo, node, hooktype, **kwargs):
347 """verify that files have expected EOLs"""
348 _checkhook(ui, repo, node, True)
349
350
351 # "checkheadshook" used to be called "hook"
352 hook = checkheadshook
353
354
355 def preupdate(ui, repo, hooktype, parent1, parent2):
356 p1node = scmutil.resolvehexnodeidprefix(repo, parent1)
357 repo.loadeol([p1node])
358 return False
359
360
361 def uisetup(ui):
362 ui.setconfig(b'hooks', b'preupdate.eol', preupdate, b'eol')
363
364
365 def extsetup(ui):
366 try:
367 extensions.find(b'win32text')
368 ui.warn(
369 _(
370 b"the eol extension is incompatible with the "
371 b"win32text extension\n"
372 )
373 )
374 except KeyError:
375 pass
376
377
378 def reposetup(ui, repo):
379 uisetup(repo.ui)
380 merge.MAYBE_USE_RUST_UPDATE = False
381
382 if not repo.local():
383 return
384 for name, fn in filters.items():
385 repo.adddatafilter(name, fn)
386
387 ui.setconfig(b'patch', b'eol', b'auto', b'eol')
388
389 class eolrepo(repo.__class__):
390 def loadeol(self, nodes):
391 eol = parseeol(self.ui, self, nodes)
392 if eol is None:
393 return None
394 eol.copytoui(self.ui)
395 return eol.match
396
397 def _hgcleardirstate(self):
398 self._eolmatch = self.loadeol([None])
399 if not self._eolmatch:
400 self._eolmatch = util.never
401 return
402
403 oldeol = None
404 try:
405 cachemtime = os.path.getmtime(self.vfs.join(b"eol.cache"))
406 except OSError:
407 cachemtime = 0
408 else:
409 olddata = self.vfs.read(b"eol.cache")
410 if olddata:
411 oldeol = eolfile(self.ui, self.root, olddata)
412
413 try:
414 eolmtime = os.path.getmtime(self.wjoin(b".hgeol"))
415 except OSError:
416 eolmtime = 0
417
418 if eolmtime >= cachemtime and eolmtime > 0:
419 self.ui.debug(b"eol: detected change in .hgeol\n")
420
421 hgeoldata = self.wvfs.read(b'.hgeol')
422 neweol = eolfile(self.ui, self.root, hgeoldata)
423
424 wlock = None
425 try:
426 wlock = self.wlock()
427 with self.dirstate.changing_files(self):
428 for f in self.dirstate:
429 if not self.dirstate.get_entry(f).maybe_clean:
430 continue
431 if oldeol is not None:
432 if not oldeol.match(f) and not neweol.match(f):
433 continue
434 oldkey = None
435 for pattern, key, m in oldeol.patterns:
436 if m(f):
437 oldkey = key
438 break
439 newkey = None
440 for pattern, key, m in neweol.patterns:
441 if m(f):
442 newkey = key
443 break
444 if oldkey == newkey:
445 continue
446 # all normal files need to be looked at again since
447 # the new .hgeol file specify a different filter
448 self.dirstate.set_possibly_dirty(f)
449 # Write the cache to update mtime and cache .hgeol
450 with self.vfs(b"eol.cache", b"w") as f:
451 f.write(hgeoldata)
452 except errormod.LockUnavailable:
453 # If we cannot lock the repository and clear the
454 # dirstate, then a commit might not see all files
455 # as modified. But if we cannot lock the
456 # repository, then we can also not make a commit,
457 # so ignore the error.
458 pass
459 finally:
460 if wlock is not None:
461 wlock.release()
462
463 def commitctx(self, ctx, error=False, origctx=None):
464 for f in sorted(ctx.added() + ctx.modified()):
465 if not self._eolmatch(f):
466 continue
467 fctx = ctx[f]
468 if fctx is None:
469 continue
470 data = fctx.data()
471 if stringutil.binary(data):
472 # We should not abort here, since the user should
473 # be able to say "** = native" to automatically
474 # have all non-binary files taken care of.
475 continue
476 if inconsistenteol(data):
477 raise errormod.Abort(
478 _(b"inconsistent newline style in %s\n") % f
479 )
480 return super().commitctx(ctx, error, origctx)
481
482 repo.__class__ = eolrepo
483 repo._hgcleardirstate()