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