##// END OF EJS Templates
merge with stable
Steve Borho -
r13625:8aec2516 merge default
parent child Browse files
Show More
@@ -1,325 +1,325
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 for f in files:
173 173 if f not in ctx:
174 174 continue
175 175 for pattern, style in self.cfg.items('patterns'):
176 176 if not match.match(repo.root, '', [pattern])(f):
177 177 continue
178 178 target = self._encode[style.upper()]
179 179 data = ctx[f].data()
180 180 if target == "to-lf" and "\r\n" in data:
181 181 raise util.Abort(_("%s should not have CRLF line endings")
182 182 % f)
183 183 elif target == "to-crlf" and singlelf.search(data):
184 184 raise util.Abort(_("%s should not have LF line endings")
185 185 % f)
186 186 # Ignore other rules for this file
187 187 break
188 188
189 189 def parseeol(ui, repo, nodes):
190 190 try:
191 191 for node in nodes:
192 192 try:
193 193 if node is None:
194 194 # Cannot use workingctx.data() since it would load
195 195 # and cache the filters before we configure them.
196 196 data = repo.wfile('.hgeol').read()
197 197 else:
198 198 data = repo[node]['.hgeol'].data()
199 199 return eolfile(ui, repo.root, data)
200 200 except (IOError, LookupError):
201 201 pass
202 202 except error.ParseError, inst:
203 203 ui.warn(_("warning: ignoring .hgeol file due to parse error "
204 204 "at %s: %s\n") % (inst.args[1], inst.args[0]))
205 205 return None
206 206
207 207 def _checkhook(ui, repo, node, headsonly):
208 208 # Get revisions to check and touched files at the same time
209 209 files = set()
210 210 revs = set()
211 211 for rev in xrange(repo[node].rev(), len(repo)):
212 212 ctx = repo[rev]
213 213 files.update(ctx.files())
214 214 revs.add(rev)
215 215 if headsonly:
216 216 for pctx in ctx.parents():
217 217 revs.discard(pctx.rev())
218 218 for rev in revs:
219 219 ctx = repo[rev]
220 220 eol = parseeol(ui, repo, [ctx.node()])
221 221 if eol:
222 222 eol.checkrev(repo, ctx, files)
223 223
224 224 def checkallhook(ui, repo, node, hooktype, **kwargs):
225 225 """verify that files have expected EOLs"""
226 226 _checkhook(ui, repo, node, False)
227 227
228 228 def checkheadshook(ui, repo, node, hooktype, **kwargs):
229 229 """verify that files have expected EOLs"""
230 230 _checkhook(ui, repo, node, True)
231 231
232 232 # "checkheadshook" used to be called "hook"
233 233 hook = checkheadshook
234 234
235 235 def preupdate(ui, repo, hooktype, parent1, parent2):
236 236 #print "preupdate for %s: %s -> %s" % (repo.root, parent1, parent2)
237 237 repo.loadeol([parent1])
238 238 return False
239 239
240 240 def uisetup(ui):
241 241 ui.setconfig('hooks', 'preupdate.eol', preupdate)
242 242
243 243 def extsetup(ui):
244 244 try:
245 245 extensions.find('win32text')
246 raise util.Abort(_("the eol extension is incompatible with the "
247 "win32text extension"))
246 ui.warn(_("the eol extension is incompatible with the "
247 "win32text extension\n"))
248 248 except KeyError:
249 249 pass
250 250
251 251
252 252 def reposetup(ui, repo):
253 253 uisetup(repo.ui)
254 254 #print "reposetup for", repo.root
255 255
256 256 if not repo.local():
257 257 return
258 258 for name, fn in filters.iteritems():
259 259 repo.adddatafilter(name, fn)
260 260
261 261 ui.setconfig('patch', 'eol', 'auto')
262 262
263 263 class eolrepo(repo.__class__):
264 264
265 265 def loadeol(self, nodes):
266 266 eol = parseeol(self.ui, self, nodes)
267 267 if eol is None:
268 268 return None
269 269 eol.setfilters(self.ui)
270 270 return eol.match
271 271
272 272 def _hgcleardirstate(self):
273 273 self._eolfile = self.loadeol([None, 'tip'])
274 274 if not self._eolfile:
275 275 self._eolfile = util.never
276 276 return
277 277
278 278 try:
279 279 cachemtime = os.path.getmtime(self.join("eol.cache"))
280 280 except OSError:
281 281 cachemtime = 0
282 282
283 283 try:
284 284 eolmtime = os.path.getmtime(self.wjoin(".hgeol"))
285 285 except OSError:
286 286 eolmtime = 0
287 287
288 288 if eolmtime > cachemtime:
289 289 ui.debug("eol: detected change in .hgeol\n")
290 290 wlock = None
291 291 try:
292 292 wlock = self.wlock()
293 293 for f in self.dirstate:
294 294 if self.dirstate[f] == 'n':
295 295 # all normal files need to be looked at
296 296 # again since the new .hgeol file might no
297 297 # longer match a file it matched before
298 298 self.dirstate.normallookup(f)
299 299 # Touch the cache to update mtime.
300 300 self.opener("eol.cache", "w").close()
301 301 wlock.release()
302 302 except error.LockUnavailable:
303 303 # If we cannot lock the repository and clear the
304 304 # dirstate, then a commit might not see all files
305 305 # as modified. But if we cannot lock the
306 306 # repository, then we can also not make a commit,
307 307 # so ignore the error.
308 308 pass
309 309
310 310 def commitctx(self, ctx, error=False):
311 311 for f in sorted(ctx.added() + ctx.modified()):
312 312 if not self._eolfile(f):
313 313 continue
314 314 data = ctx[f].data()
315 315 if util.binary(data):
316 316 # We should not abort here, since the user should
317 317 # be able to say "** = native" to automatically
318 318 # have all non-binary files taken care of.
319 319 continue
320 320 if inconsistenteol(data):
321 321 raise util.Abort(_("inconsistent newline style "
322 322 "in %s\n" % f))
323 323 return super(eolrepo, self).commitctx(ctx, error)
324 324 repo.__class__ = eolrepo
325 325 repo._hgcleardirstate()
General Comments 0
You need to be logged in to leave comments. Login now