##// END OF EJS Templates
scmutil.readonlyvfs: implement join...
Siddharth Agarwal -
r26156:a112fffd default
parent child Browse files
Show More
@@ -1,1127 +1,1129 b''
1 # scmutil.py - Mercurial core utility functions
1 # scmutil.py - Mercurial core utility functions
2 #
2 #
3 # Copyright Matt Mackall <mpm@selenic.com>
3 # Copyright Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
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.
6 # GNU General Public License version 2 or any later version.
7
7
8 from i18n import _
8 from i18n import _
9 from mercurial.node import wdirrev
9 from mercurial.node import wdirrev
10 import util, error, osutil, revset, similar, encoding, phases
10 import util, error, osutil, revset, similar, encoding, phases
11 import pathutil
11 import pathutil
12 import match as matchmod
12 import match as matchmod
13 import os, errno, re, glob, tempfile, shutil, stat
13 import os, errno, re, glob, tempfile, shutil, stat
14
14
15 if os.name == 'nt':
15 if os.name == 'nt':
16 import scmwindows as scmplatform
16 import scmwindows as scmplatform
17 else:
17 else:
18 import scmposix as scmplatform
18 import scmposix as scmplatform
19
19
20 systemrcpath = scmplatform.systemrcpath
20 systemrcpath = scmplatform.systemrcpath
21 userrcpath = scmplatform.userrcpath
21 userrcpath = scmplatform.userrcpath
22
22
23 class status(tuple):
23 class status(tuple):
24 '''Named tuple with a list of files per status. The 'deleted', 'unknown'
24 '''Named tuple with a list of files per status. The 'deleted', 'unknown'
25 and 'ignored' properties are only relevant to the working copy.
25 and 'ignored' properties are only relevant to the working copy.
26 '''
26 '''
27
27
28 __slots__ = ()
28 __slots__ = ()
29
29
30 def __new__(cls, modified, added, removed, deleted, unknown, ignored,
30 def __new__(cls, modified, added, removed, deleted, unknown, ignored,
31 clean):
31 clean):
32 return tuple.__new__(cls, (modified, added, removed, deleted, unknown,
32 return tuple.__new__(cls, (modified, added, removed, deleted, unknown,
33 ignored, clean))
33 ignored, clean))
34
34
35 @property
35 @property
36 def modified(self):
36 def modified(self):
37 '''files that have been modified'''
37 '''files that have been modified'''
38 return self[0]
38 return self[0]
39
39
40 @property
40 @property
41 def added(self):
41 def added(self):
42 '''files that have been added'''
42 '''files that have been added'''
43 return self[1]
43 return self[1]
44
44
45 @property
45 @property
46 def removed(self):
46 def removed(self):
47 '''files that have been removed'''
47 '''files that have been removed'''
48 return self[2]
48 return self[2]
49
49
50 @property
50 @property
51 def deleted(self):
51 def deleted(self):
52 '''files that are in the dirstate, but have been deleted from the
52 '''files that are in the dirstate, but have been deleted from the
53 working copy (aka "missing")
53 working copy (aka "missing")
54 '''
54 '''
55 return self[3]
55 return self[3]
56
56
57 @property
57 @property
58 def unknown(self):
58 def unknown(self):
59 '''files not in the dirstate that are not ignored'''
59 '''files not in the dirstate that are not ignored'''
60 return self[4]
60 return self[4]
61
61
62 @property
62 @property
63 def ignored(self):
63 def ignored(self):
64 '''files not in the dirstate that are ignored (by _dirignore())'''
64 '''files not in the dirstate that are ignored (by _dirignore())'''
65 return self[5]
65 return self[5]
66
66
67 @property
67 @property
68 def clean(self):
68 def clean(self):
69 '''files that have not been modified'''
69 '''files that have not been modified'''
70 return self[6]
70 return self[6]
71
71
72 def __repr__(self, *args, **kwargs):
72 def __repr__(self, *args, **kwargs):
73 return (('<status modified=%r, added=%r, removed=%r, deleted=%r, '
73 return (('<status modified=%r, added=%r, removed=%r, deleted=%r, '
74 'unknown=%r, ignored=%r, clean=%r>') % self)
74 'unknown=%r, ignored=%r, clean=%r>') % self)
75
75
76 def itersubrepos(ctx1, ctx2):
76 def itersubrepos(ctx1, ctx2):
77 """find subrepos in ctx1 or ctx2"""
77 """find subrepos in ctx1 or ctx2"""
78 # Create a (subpath, ctx) mapping where we prefer subpaths from
78 # Create a (subpath, ctx) mapping where we prefer subpaths from
79 # ctx1. The subpaths from ctx2 are important when the .hgsub file
79 # ctx1. The subpaths from ctx2 are important when the .hgsub file
80 # has been modified (in ctx2) but not yet committed (in ctx1).
80 # has been modified (in ctx2) but not yet committed (in ctx1).
81 subpaths = dict.fromkeys(ctx2.substate, ctx2)
81 subpaths = dict.fromkeys(ctx2.substate, ctx2)
82 subpaths.update(dict.fromkeys(ctx1.substate, ctx1))
82 subpaths.update(dict.fromkeys(ctx1.substate, ctx1))
83
83
84 missing = set()
84 missing = set()
85
85
86 for subpath in ctx2.substate:
86 for subpath in ctx2.substate:
87 if subpath not in ctx1.substate:
87 if subpath not in ctx1.substate:
88 del subpaths[subpath]
88 del subpaths[subpath]
89 missing.add(subpath)
89 missing.add(subpath)
90
90
91 for subpath, ctx in sorted(subpaths.iteritems()):
91 for subpath, ctx in sorted(subpaths.iteritems()):
92 yield subpath, ctx.sub(subpath)
92 yield subpath, ctx.sub(subpath)
93
93
94 # Yield an empty subrepo based on ctx1 for anything only in ctx2. That way,
94 # Yield an empty subrepo based on ctx1 for anything only in ctx2. That way,
95 # status and diff will have an accurate result when it does
95 # status and diff will have an accurate result when it does
96 # 'sub.{status|diff}(rev2)'. Otherwise, the ctx2 subrepo is compared
96 # 'sub.{status|diff}(rev2)'. Otherwise, the ctx2 subrepo is compared
97 # against itself.
97 # against itself.
98 for subpath in missing:
98 for subpath in missing:
99 yield subpath, ctx2.nullsub(subpath, ctx1)
99 yield subpath, ctx2.nullsub(subpath, ctx1)
100
100
101 def nochangesfound(ui, repo, excluded=None):
101 def nochangesfound(ui, repo, excluded=None):
102 '''Report no changes for push/pull, excluded is None or a list of
102 '''Report no changes for push/pull, excluded is None or a list of
103 nodes excluded from the push/pull.
103 nodes excluded from the push/pull.
104 '''
104 '''
105 secretlist = []
105 secretlist = []
106 if excluded:
106 if excluded:
107 for n in excluded:
107 for n in excluded:
108 if n not in repo:
108 if n not in repo:
109 # discovery should not have included the filtered revision,
109 # discovery should not have included the filtered revision,
110 # we have to explicitly exclude it until discovery is cleanup.
110 # we have to explicitly exclude it until discovery is cleanup.
111 continue
111 continue
112 ctx = repo[n]
112 ctx = repo[n]
113 if ctx.phase() >= phases.secret and not ctx.extinct():
113 if ctx.phase() >= phases.secret and not ctx.extinct():
114 secretlist.append(n)
114 secretlist.append(n)
115
115
116 if secretlist:
116 if secretlist:
117 ui.status(_("no changes found (ignored %d secret changesets)\n")
117 ui.status(_("no changes found (ignored %d secret changesets)\n")
118 % len(secretlist))
118 % len(secretlist))
119 else:
119 else:
120 ui.status(_("no changes found\n"))
120 ui.status(_("no changes found\n"))
121
121
122 def checknewlabel(repo, lbl, kind):
122 def checknewlabel(repo, lbl, kind):
123 # Do not use the "kind" parameter in ui output.
123 # Do not use the "kind" parameter in ui output.
124 # It makes strings difficult to translate.
124 # It makes strings difficult to translate.
125 if lbl in ['tip', '.', 'null']:
125 if lbl in ['tip', '.', 'null']:
126 raise util.Abort(_("the name '%s' is reserved") % lbl)
126 raise util.Abort(_("the name '%s' is reserved") % lbl)
127 for c in (':', '\0', '\n', '\r'):
127 for c in (':', '\0', '\n', '\r'):
128 if c in lbl:
128 if c in lbl:
129 raise util.Abort(_("%r cannot be used in a name") % c)
129 raise util.Abort(_("%r cannot be used in a name") % c)
130 try:
130 try:
131 int(lbl)
131 int(lbl)
132 raise util.Abort(_("cannot use an integer as a name"))
132 raise util.Abort(_("cannot use an integer as a name"))
133 except ValueError:
133 except ValueError:
134 pass
134 pass
135
135
136 def checkfilename(f):
136 def checkfilename(f):
137 '''Check that the filename f is an acceptable filename for a tracked file'''
137 '''Check that the filename f is an acceptable filename for a tracked file'''
138 if '\r' in f or '\n' in f:
138 if '\r' in f or '\n' in f:
139 raise util.Abort(_("'\\n' and '\\r' disallowed in filenames: %r") % f)
139 raise util.Abort(_("'\\n' and '\\r' disallowed in filenames: %r") % f)
140
140
141 def checkportable(ui, f):
141 def checkportable(ui, f):
142 '''Check if filename f is portable and warn or abort depending on config'''
142 '''Check if filename f is portable and warn or abort depending on config'''
143 checkfilename(f)
143 checkfilename(f)
144 abort, warn = checkportabilityalert(ui)
144 abort, warn = checkportabilityalert(ui)
145 if abort or warn:
145 if abort or warn:
146 msg = util.checkwinfilename(f)
146 msg = util.checkwinfilename(f)
147 if msg:
147 if msg:
148 msg = "%s: %r" % (msg, f)
148 msg = "%s: %r" % (msg, f)
149 if abort:
149 if abort:
150 raise util.Abort(msg)
150 raise util.Abort(msg)
151 ui.warn(_("warning: %s\n") % msg)
151 ui.warn(_("warning: %s\n") % msg)
152
152
153 def checkportabilityalert(ui):
153 def checkportabilityalert(ui):
154 '''check if the user's config requests nothing, a warning, or abort for
154 '''check if the user's config requests nothing, a warning, or abort for
155 non-portable filenames'''
155 non-portable filenames'''
156 val = ui.config('ui', 'portablefilenames', 'warn')
156 val = ui.config('ui', 'portablefilenames', 'warn')
157 lval = val.lower()
157 lval = val.lower()
158 bval = util.parsebool(val)
158 bval = util.parsebool(val)
159 abort = os.name == 'nt' or lval == 'abort'
159 abort = os.name == 'nt' or lval == 'abort'
160 warn = bval or lval == 'warn'
160 warn = bval or lval == 'warn'
161 if bval is None and not (warn or abort or lval == 'ignore'):
161 if bval is None and not (warn or abort or lval == 'ignore'):
162 raise error.ConfigError(
162 raise error.ConfigError(
163 _("ui.portablefilenames value is invalid ('%s')") % val)
163 _("ui.portablefilenames value is invalid ('%s')") % val)
164 return abort, warn
164 return abort, warn
165
165
166 class casecollisionauditor(object):
166 class casecollisionauditor(object):
167 def __init__(self, ui, abort, dirstate):
167 def __init__(self, ui, abort, dirstate):
168 self._ui = ui
168 self._ui = ui
169 self._abort = abort
169 self._abort = abort
170 allfiles = '\0'.join(dirstate._map)
170 allfiles = '\0'.join(dirstate._map)
171 self._loweredfiles = set(encoding.lower(allfiles).split('\0'))
171 self._loweredfiles = set(encoding.lower(allfiles).split('\0'))
172 self._dirstate = dirstate
172 self._dirstate = dirstate
173 # The purpose of _newfiles is so that we don't complain about
173 # The purpose of _newfiles is so that we don't complain about
174 # case collisions if someone were to call this object with the
174 # case collisions if someone were to call this object with the
175 # same filename twice.
175 # same filename twice.
176 self._newfiles = set()
176 self._newfiles = set()
177
177
178 def __call__(self, f):
178 def __call__(self, f):
179 if f in self._newfiles:
179 if f in self._newfiles:
180 return
180 return
181 fl = encoding.lower(f)
181 fl = encoding.lower(f)
182 if fl in self._loweredfiles and f not in self._dirstate:
182 if fl in self._loweredfiles and f not in self._dirstate:
183 msg = _('possible case-folding collision for %s') % f
183 msg = _('possible case-folding collision for %s') % f
184 if self._abort:
184 if self._abort:
185 raise util.Abort(msg)
185 raise util.Abort(msg)
186 self._ui.warn(_("warning: %s\n") % msg)
186 self._ui.warn(_("warning: %s\n") % msg)
187 self._loweredfiles.add(fl)
187 self._loweredfiles.add(fl)
188 self._newfiles.add(f)
188 self._newfiles.add(f)
189
189
190 def filteredhash(repo, maxrev):
190 def filteredhash(repo, maxrev):
191 """build hash of filtered revisions in the current repoview.
191 """build hash of filtered revisions in the current repoview.
192
192
193 Multiple caches perform up-to-date validation by checking that the
193 Multiple caches perform up-to-date validation by checking that the
194 tiprev and tipnode stored in the cache file match the current repository.
194 tiprev and tipnode stored in the cache file match the current repository.
195 However, this is not sufficient for validating repoviews because the set
195 However, this is not sufficient for validating repoviews because the set
196 of revisions in the view may change without the repository tiprev and
196 of revisions in the view may change without the repository tiprev and
197 tipnode changing.
197 tipnode changing.
198
198
199 This function hashes all the revs filtered from the view and returns
199 This function hashes all the revs filtered from the view and returns
200 that SHA-1 digest.
200 that SHA-1 digest.
201 """
201 """
202 cl = repo.changelog
202 cl = repo.changelog
203 if not cl.filteredrevs:
203 if not cl.filteredrevs:
204 return None
204 return None
205 key = None
205 key = None
206 revs = sorted(r for r in cl.filteredrevs if r <= maxrev)
206 revs = sorted(r for r in cl.filteredrevs if r <= maxrev)
207 if revs:
207 if revs:
208 s = util.sha1()
208 s = util.sha1()
209 for rev in revs:
209 for rev in revs:
210 s.update('%s;' % rev)
210 s.update('%s;' % rev)
211 key = s.digest()
211 key = s.digest()
212 return key
212 return key
213
213
214 class abstractvfs(object):
214 class abstractvfs(object):
215 """Abstract base class; cannot be instantiated"""
215 """Abstract base class; cannot be instantiated"""
216
216
217 def __init__(self, *args, **kwargs):
217 def __init__(self, *args, **kwargs):
218 '''Prevent instantiation; don't call this from subclasses.'''
218 '''Prevent instantiation; don't call this from subclasses.'''
219 raise NotImplementedError('attempted instantiating ' + str(type(self)))
219 raise NotImplementedError('attempted instantiating ' + str(type(self)))
220
220
221 def tryread(self, path):
221 def tryread(self, path):
222 '''gracefully return an empty string for missing files'''
222 '''gracefully return an empty string for missing files'''
223 try:
223 try:
224 return self.read(path)
224 return self.read(path)
225 except IOError as inst:
225 except IOError as inst:
226 if inst.errno != errno.ENOENT:
226 if inst.errno != errno.ENOENT:
227 raise
227 raise
228 return ""
228 return ""
229
229
230 def tryreadlines(self, path, mode='rb'):
230 def tryreadlines(self, path, mode='rb'):
231 '''gracefully return an empty array for missing files'''
231 '''gracefully return an empty array for missing files'''
232 try:
232 try:
233 return self.readlines(path, mode=mode)
233 return self.readlines(path, mode=mode)
234 except IOError as inst:
234 except IOError as inst:
235 if inst.errno != errno.ENOENT:
235 if inst.errno != errno.ENOENT:
236 raise
236 raise
237 return []
237 return []
238
238
239 def open(self, path, mode="r", text=False, atomictemp=False,
239 def open(self, path, mode="r", text=False, atomictemp=False,
240 notindexed=False):
240 notindexed=False):
241 '''Open ``path`` file, which is relative to vfs root.
241 '''Open ``path`` file, which is relative to vfs root.
242
242
243 Newly created directories are marked as "not to be indexed by
243 Newly created directories are marked as "not to be indexed by
244 the content indexing service", if ``notindexed`` is specified
244 the content indexing service", if ``notindexed`` is specified
245 for "write" mode access.
245 for "write" mode access.
246 '''
246 '''
247 self.open = self.__call__
247 self.open = self.__call__
248 return self.__call__(path, mode, text, atomictemp, notindexed)
248 return self.__call__(path, mode, text, atomictemp, notindexed)
249
249
250 def read(self, path):
250 def read(self, path):
251 fp = self(path, 'rb')
251 fp = self(path, 'rb')
252 try:
252 try:
253 return fp.read()
253 return fp.read()
254 finally:
254 finally:
255 fp.close()
255 fp.close()
256
256
257 def readlines(self, path, mode='rb'):
257 def readlines(self, path, mode='rb'):
258 fp = self(path, mode=mode)
258 fp = self(path, mode=mode)
259 try:
259 try:
260 return fp.readlines()
260 return fp.readlines()
261 finally:
261 finally:
262 fp.close()
262 fp.close()
263
263
264 def write(self, path, data):
264 def write(self, path, data):
265 fp = self(path, 'wb')
265 fp = self(path, 'wb')
266 try:
266 try:
267 return fp.write(data)
267 return fp.write(data)
268 finally:
268 finally:
269 fp.close()
269 fp.close()
270
270
271 def writelines(self, path, data, mode='wb', notindexed=False):
271 def writelines(self, path, data, mode='wb', notindexed=False):
272 fp = self(path, mode=mode, notindexed=notindexed)
272 fp = self(path, mode=mode, notindexed=notindexed)
273 try:
273 try:
274 return fp.writelines(data)
274 return fp.writelines(data)
275 finally:
275 finally:
276 fp.close()
276 fp.close()
277
277
278 def append(self, path, data):
278 def append(self, path, data):
279 fp = self(path, 'ab')
279 fp = self(path, 'ab')
280 try:
280 try:
281 return fp.write(data)
281 return fp.write(data)
282 finally:
282 finally:
283 fp.close()
283 fp.close()
284
284
285 def basename(self, path):
285 def basename(self, path):
286 """return base element of a path (as os.path.basename would do)
286 """return base element of a path (as os.path.basename would do)
287
287
288 This exists to allow handling of strange encoding if needed."""
288 This exists to allow handling of strange encoding if needed."""
289 return os.path.basename(path)
289 return os.path.basename(path)
290
290
291 def chmod(self, path, mode):
291 def chmod(self, path, mode):
292 return os.chmod(self.join(path), mode)
292 return os.chmod(self.join(path), mode)
293
293
294 def dirname(self, path):
294 def dirname(self, path):
295 """return dirname element of a path (as os.path.dirname would do)
295 """return dirname element of a path (as os.path.dirname would do)
296
296
297 This exists to allow handling of strange encoding if needed."""
297 This exists to allow handling of strange encoding if needed."""
298 return os.path.dirname(path)
298 return os.path.dirname(path)
299
299
300 def exists(self, path=None):
300 def exists(self, path=None):
301 return os.path.exists(self.join(path))
301 return os.path.exists(self.join(path))
302
302
303 def fstat(self, fp):
303 def fstat(self, fp):
304 return util.fstat(fp)
304 return util.fstat(fp)
305
305
306 def isdir(self, path=None):
306 def isdir(self, path=None):
307 return os.path.isdir(self.join(path))
307 return os.path.isdir(self.join(path))
308
308
309 def isfile(self, path=None):
309 def isfile(self, path=None):
310 return os.path.isfile(self.join(path))
310 return os.path.isfile(self.join(path))
311
311
312 def islink(self, path=None):
312 def islink(self, path=None):
313 return os.path.islink(self.join(path))
313 return os.path.islink(self.join(path))
314
314
315 def reljoin(self, *paths):
315 def reljoin(self, *paths):
316 """join various elements of a path together (as os.path.join would do)
316 """join various elements of a path together (as os.path.join would do)
317
317
318 The vfs base is not injected so that path stay relative. This exists
318 The vfs base is not injected so that path stay relative. This exists
319 to allow handling of strange encoding if needed."""
319 to allow handling of strange encoding if needed."""
320 return os.path.join(*paths)
320 return os.path.join(*paths)
321
321
322 def split(self, path):
322 def split(self, path):
323 """split top-most element of a path (as os.path.split would do)
323 """split top-most element of a path (as os.path.split would do)
324
324
325 This exists to allow handling of strange encoding if needed."""
325 This exists to allow handling of strange encoding if needed."""
326 return os.path.split(path)
326 return os.path.split(path)
327
327
328 def lexists(self, path=None):
328 def lexists(self, path=None):
329 return os.path.lexists(self.join(path))
329 return os.path.lexists(self.join(path))
330
330
331 def lstat(self, path=None):
331 def lstat(self, path=None):
332 return os.lstat(self.join(path))
332 return os.lstat(self.join(path))
333
333
334 def listdir(self, path=None):
334 def listdir(self, path=None):
335 return os.listdir(self.join(path))
335 return os.listdir(self.join(path))
336
336
337 def makedir(self, path=None, notindexed=True):
337 def makedir(self, path=None, notindexed=True):
338 return util.makedir(self.join(path), notindexed)
338 return util.makedir(self.join(path), notindexed)
339
339
340 def makedirs(self, path=None, mode=None):
340 def makedirs(self, path=None, mode=None):
341 return util.makedirs(self.join(path), mode)
341 return util.makedirs(self.join(path), mode)
342
342
343 def makelock(self, info, path):
343 def makelock(self, info, path):
344 return util.makelock(info, self.join(path))
344 return util.makelock(info, self.join(path))
345
345
346 def mkdir(self, path=None):
346 def mkdir(self, path=None):
347 return os.mkdir(self.join(path))
347 return os.mkdir(self.join(path))
348
348
349 def mkstemp(self, suffix='', prefix='tmp', dir=None, text=False):
349 def mkstemp(self, suffix='', prefix='tmp', dir=None, text=False):
350 fd, name = tempfile.mkstemp(suffix=suffix, prefix=prefix,
350 fd, name = tempfile.mkstemp(suffix=suffix, prefix=prefix,
351 dir=self.join(dir), text=text)
351 dir=self.join(dir), text=text)
352 dname, fname = util.split(name)
352 dname, fname = util.split(name)
353 if dir:
353 if dir:
354 return fd, os.path.join(dir, fname)
354 return fd, os.path.join(dir, fname)
355 else:
355 else:
356 return fd, fname
356 return fd, fname
357
357
358 def readdir(self, path=None, stat=None, skip=None):
358 def readdir(self, path=None, stat=None, skip=None):
359 return osutil.listdir(self.join(path), stat, skip)
359 return osutil.listdir(self.join(path), stat, skip)
360
360
361 def readlock(self, path):
361 def readlock(self, path):
362 return util.readlock(self.join(path))
362 return util.readlock(self.join(path))
363
363
364 def rename(self, src, dst):
364 def rename(self, src, dst):
365 return util.rename(self.join(src), self.join(dst))
365 return util.rename(self.join(src), self.join(dst))
366
366
367 def readlink(self, path):
367 def readlink(self, path):
368 return os.readlink(self.join(path))
368 return os.readlink(self.join(path))
369
369
370 def removedirs(self, path=None):
370 def removedirs(self, path=None):
371 """Remove a leaf directory and all empty intermediate ones
371 """Remove a leaf directory and all empty intermediate ones
372 """
372 """
373 return util.removedirs(self.join(path))
373 return util.removedirs(self.join(path))
374
374
375 def rmtree(self, path=None, ignore_errors=False, forcibly=False):
375 def rmtree(self, path=None, ignore_errors=False, forcibly=False):
376 """Remove a directory tree recursively
376 """Remove a directory tree recursively
377
377
378 If ``forcibly``, this tries to remove READ-ONLY files, too.
378 If ``forcibly``, this tries to remove READ-ONLY files, too.
379 """
379 """
380 if forcibly:
380 if forcibly:
381 def onerror(function, path, excinfo):
381 def onerror(function, path, excinfo):
382 if function is not os.remove:
382 if function is not os.remove:
383 raise
383 raise
384 # read-only files cannot be unlinked under Windows
384 # read-only files cannot be unlinked under Windows
385 s = os.stat(path)
385 s = os.stat(path)
386 if (s.st_mode & stat.S_IWRITE) != 0:
386 if (s.st_mode & stat.S_IWRITE) != 0:
387 raise
387 raise
388 os.chmod(path, stat.S_IMODE(s.st_mode) | stat.S_IWRITE)
388 os.chmod(path, stat.S_IMODE(s.st_mode) | stat.S_IWRITE)
389 os.remove(path)
389 os.remove(path)
390 else:
390 else:
391 onerror = None
391 onerror = None
392 return shutil.rmtree(self.join(path),
392 return shutil.rmtree(self.join(path),
393 ignore_errors=ignore_errors, onerror=onerror)
393 ignore_errors=ignore_errors, onerror=onerror)
394
394
395 def setflags(self, path, l, x):
395 def setflags(self, path, l, x):
396 return util.setflags(self.join(path), l, x)
396 return util.setflags(self.join(path), l, x)
397
397
398 def stat(self, path=None):
398 def stat(self, path=None):
399 return os.stat(self.join(path))
399 return os.stat(self.join(path))
400
400
401 def unlink(self, path=None):
401 def unlink(self, path=None):
402 return util.unlink(self.join(path))
402 return util.unlink(self.join(path))
403
403
404 def unlinkpath(self, path=None, ignoremissing=False):
404 def unlinkpath(self, path=None, ignoremissing=False):
405 return util.unlinkpath(self.join(path), ignoremissing)
405 return util.unlinkpath(self.join(path), ignoremissing)
406
406
407 def utime(self, path=None, t=None):
407 def utime(self, path=None, t=None):
408 return os.utime(self.join(path), t)
408 return os.utime(self.join(path), t)
409
409
410 def walk(self, path=None, onerror=None):
410 def walk(self, path=None, onerror=None):
411 """Yield (dirpath, dirs, files) tuple for each directories under path
411 """Yield (dirpath, dirs, files) tuple for each directories under path
412
412
413 ``dirpath`` is relative one from the root of this vfs. This
413 ``dirpath`` is relative one from the root of this vfs. This
414 uses ``os.sep`` as path separator, even you specify POSIX
414 uses ``os.sep`` as path separator, even you specify POSIX
415 style ``path``.
415 style ``path``.
416
416
417 "The root of this vfs" is represented as empty ``dirpath``.
417 "The root of this vfs" is represented as empty ``dirpath``.
418 """
418 """
419 root = os.path.normpath(self.join(None))
419 root = os.path.normpath(self.join(None))
420 # when dirpath == root, dirpath[prefixlen:] becomes empty
420 # when dirpath == root, dirpath[prefixlen:] becomes empty
421 # because len(dirpath) < prefixlen.
421 # because len(dirpath) < prefixlen.
422 prefixlen = len(pathutil.normasprefix(root))
422 prefixlen = len(pathutil.normasprefix(root))
423 for dirpath, dirs, files in os.walk(self.join(path), onerror=onerror):
423 for dirpath, dirs, files in os.walk(self.join(path), onerror=onerror):
424 yield (dirpath[prefixlen:], dirs, files)
424 yield (dirpath[prefixlen:], dirs, files)
425
425
426 class vfs(abstractvfs):
426 class vfs(abstractvfs):
427 '''Operate files relative to a base directory
427 '''Operate files relative to a base directory
428
428
429 This class is used to hide the details of COW semantics and
429 This class is used to hide the details of COW semantics and
430 remote file access from higher level code.
430 remote file access from higher level code.
431 '''
431 '''
432 def __init__(self, base, audit=True, expandpath=False, realpath=False):
432 def __init__(self, base, audit=True, expandpath=False, realpath=False):
433 if expandpath:
433 if expandpath:
434 base = util.expandpath(base)
434 base = util.expandpath(base)
435 if realpath:
435 if realpath:
436 base = os.path.realpath(base)
436 base = os.path.realpath(base)
437 self.base = base
437 self.base = base
438 self._setmustaudit(audit)
438 self._setmustaudit(audit)
439 self.createmode = None
439 self.createmode = None
440 self._trustnlink = None
440 self._trustnlink = None
441
441
442 def _getmustaudit(self):
442 def _getmustaudit(self):
443 return self._audit
443 return self._audit
444
444
445 def _setmustaudit(self, onoff):
445 def _setmustaudit(self, onoff):
446 self._audit = onoff
446 self._audit = onoff
447 if onoff:
447 if onoff:
448 self.audit = pathutil.pathauditor(self.base)
448 self.audit = pathutil.pathauditor(self.base)
449 else:
449 else:
450 self.audit = util.always
450 self.audit = util.always
451
451
452 mustaudit = property(_getmustaudit, _setmustaudit)
452 mustaudit = property(_getmustaudit, _setmustaudit)
453
453
454 @util.propertycache
454 @util.propertycache
455 def _cansymlink(self):
455 def _cansymlink(self):
456 return util.checklink(self.base)
456 return util.checklink(self.base)
457
457
458 @util.propertycache
458 @util.propertycache
459 def _chmod(self):
459 def _chmod(self):
460 return util.checkexec(self.base)
460 return util.checkexec(self.base)
461
461
462 def _fixfilemode(self, name):
462 def _fixfilemode(self, name):
463 if self.createmode is None or not self._chmod:
463 if self.createmode is None or not self._chmod:
464 return
464 return
465 os.chmod(name, self.createmode & 0o666)
465 os.chmod(name, self.createmode & 0o666)
466
466
467 def __call__(self, path, mode="r", text=False, atomictemp=False,
467 def __call__(self, path, mode="r", text=False, atomictemp=False,
468 notindexed=False):
468 notindexed=False):
469 '''Open ``path`` file, which is relative to vfs root.
469 '''Open ``path`` file, which is relative to vfs root.
470
470
471 Newly created directories are marked as "not to be indexed by
471 Newly created directories are marked as "not to be indexed by
472 the content indexing service", if ``notindexed`` is specified
472 the content indexing service", if ``notindexed`` is specified
473 for "write" mode access.
473 for "write" mode access.
474 '''
474 '''
475 if self._audit:
475 if self._audit:
476 r = util.checkosfilename(path)
476 r = util.checkosfilename(path)
477 if r:
477 if r:
478 raise util.Abort("%s: %r" % (r, path))
478 raise util.Abort("%s: %r" % (r, path))
479 self.audit(path)
479 self.audit(path)
480 f = self.join(path)
480 f = self.join(path)
481
481
482 if not text and "b" not in mode:
482 if not text and "b" not in mode:
483 mode += "b" # for that other OS
483 mode += "b" # for that other OS
484
484
485 nlink = -1
485 nlink = -1
486 if mode not in ('r', 'rb'):
486 if mode not in ('r', 'rb'):
487 dirname, basename = util.split(f)
487 dirname, basename = util.split(f)
488 # If basename is empty, then the path is malformed because it points
488 # If basename is empty, then the path is malformed because it points
489 # to a directory. Let the posixfile() call below raise IOError.
489 # to a directory. Let the posixfile() call below raise IOError.
490 if basename:
490 if basename:
491 if atomictemp:
491 if atomictemp:
492 util.ensuredirs(dirname, self.createmode, notindexed)
492 util.ensuredirs(dirname, self.createmode, notindexed)
493 return util.atomictempfile(f, mode, self.createmode)
493 return util.atomictempfile(f, mode, self.createmode)
494 try:
494 try:
495 if 'w' in mode:
495 if 'w' in mode:
496 util.unlink(f)
496 util.unlink(f)
497 nlink = 0
497 nlink = 0
498 else:
498 else:
499 # nlinks() may behave differently for files on Windows
499 # nlinks() may behave differently for files on Windows
500 # shares if the file is open.
500 # shares if the file is open.
501 fd = util.posixfile(f)
501 fd = util.posixfile(f)
502 nlink = util.nlinks(f)
502 nlink = util.nlinks(f)
503 if nlink < 1:
503 if nlink < 1:
504 nlink = 2 # force mktempcopy (issue1922)
504 nlink = 2 # force mktempcopy (issue1922)
505 fd.close()
505 fd.close()
506 except (OSError, IOError) as e:
506 except (OSError, IOError) as e:
507 if e.errno != errno.ENOENT:
507 if e.errno != errno.ENOENT:
508 raise
508 raise
509 nlink = 0
509 nlink = 0
510 util.ensuredirs(dirname, self.createmode, notindexed)
510 util.ensuredirs(dirname, self.createmode, notindexed)
511 if nlink > 0:
511 if nlink > 0:
512 if self._trustnlink is None:
512 if self._trustnlink is None:
513 self._trustnlink = nlink > 1 or util.checknlink(f)
513 self._trustnlink = nlink > 1 or util.checknlink(f)
514 if nlink > 1 or not self._trustnlink:
514 if nlink > 1 or not self._trustnlink:
515 util.rename(util.mktempcopy(f), f)
515 util.rename(util.mktempcopy(f), f)
516 fp = util.posixfile(f, mode)
516 fp = util.posixfile(f, mode)
517 if nlink == 0:
517 if nlink == 0:
518 self._fixfilemode(f)
518 self._fixfilemode(f)
519 return fp
519 return fp
520
520
521 def symlink(self, src, dst):
521 def symlink(self, src, dst):
522 self.audit(dst)
522 self.audit(dst)
523 linkname = self.join(dst)
523 linkname = self.join(dst)
524 try:
524 try:
525 os.unlink(linkname)
525 os.unlink(linkname)
526 except OSError:
526 except OSError:
527 pass
527 pass
528
528
529 util.ensuredirs(os.path.dirname(linkname), self.createmode)
529 util.ensuredirs(os.path.dirname(linkname), self.createmode)
530
530
531 if self._cansymlink:
531 if self._cansymlink:
532 try:
532 try:
533 os.symlink(src, linkname)
533 os.symlink(src, linkname)
534 except OSError as err:
534 except OSError as err:
535 raise OSError(err.errno, _('could not symlink to %r: %s') %
535 raise OSError(err.errno, _('could not symlink to %r: %s') %
536 (src, err.strerror), linkname)
536 (src, err.strerror), linkname)
537 else:
537 else:
538 self.write(dst, src)
538 self.write(dst, src)
539
539
540 def join(self, path, *insidef):
540 def join(self, path, *insidef):
541 if path:
541 if path:
542 return os.path.join(self.base, path, *insidef)
542 return os.path.join(self.base, path, *insidef)
543 else:
543 else:
544 return self.base
544 return self.base
545
545
546 opener = vfs
546 opener = vfs
547
547
548 class auditvfs(object):
548 class auditvfs(object):
549 def __init__(self, vfs):
549 def __init__(self, vfs):
550 self.vfs = vfs
550 self.vfs = vfs
551
551
552 def _getmustaudit(self):
552 def _getmustaudit(self):
553 return self.vfs.mustaudit
553 return self.vfs.mustaudit
554
554
555 def _setmustaudit(self, onoff):
555 def _setmustaudit(self, onoff):
556 self.vfs.mustaudit = onoff
556 self.vfs.mustaudit = onoff
557
557
558 mustaudit = property(_getmustaudit, _setmustaudit)
558 mustaudit = property(_getmustaudit, _setmustaudit)
559
559
560 class filtervfs(abstractvfs, auditvfs):
560 class filtervfs(abstractvfs, auditvfs):
561 '''Wrapper vfs for filtering filenames with a function.'''
561 '''Wrapper vfs for filtering filenames with a function.'''
562
562
563 def __init__(self, vfs, filter):
563 def __init__(self, vfs, filter):
564 auditvfs.__init__(self, vfs)
564 auditvfs.__init__(self, vfs)
565 self._filter = filter
565 self._filter = filter
566
566
567 def __call__(self, path, *args, **kwargs):
567 def __call__(self, path, *args, **kwargs):
568 return self.vfs(self._filter(path), *args, **kwargs)
568 return self.vfs(self._filter(path), *args, **kwargs)
569
569
570 def join(self, path, *insidef):
570 def join(self, path, *insidef):
571 if path:
571 if path:
572 return self.vfs.join(self._filter(self.vfs.reljoin(path, *insidef)))
572 return self.vfs.join(self._filter(self.vfs.reljoin(path, *insidef)))
573 else:
573 else:
574 return self.vfs.join(path)
574 return self.vfs.join(path)
575
575
576 filteropener = filtervfs
576 filteropener = filtervfs
577
577
578 class readonlyvfs(abstractvfs, auditvfs):
578 class readonlyvfs(abstractvfs, auditvfs):
579 '''Wrapper vfs preventing any writing.'''
579 '''Wrapper vfs preventing any writing.'''
580
580
581 def __init__(self, vfs):
581 def __init__(self, vfs):
582 auditvfs.__init__(self, vfs)
582 auditvfs.__init__(self, vfs)
583
583
584 def __call__(self, path, mode='r', *args, **kw):
584 def __call__(self, path, mode='r', *args, **kw):
585 if mode not in ('r', 'rb'):
585 if mode not in ('r', 'rb'):
586 raise util.Abort('this vfs is read only')
586 raise util.Abort('this vfs is read only')
587 return self.vfs(path, mode, *args, **kw)
587 return self.vfs(path, mode, *args, **kw)
588
588
589 def join(self, path, *insidef):
590 return self.vfs.join(path, *insidef)
589
591
590 def walkrepos(path, followsym=False, seen_dirs=None, recurse=False):
592 def walkrepos(path, followsym=False, seen_dirs=None, recurse=False):
591 '''yield every hg repository under path, always recursively.
593 '''yield every hg repository under path, always recursively.
592 The recurse flag will only control recursion into repo working dirs'''
594 The recurse flag will only control recursion into repo working dirs'''
593 def errhandler(err):
595 def errhandler(err):
594 if err.filename == path:
596 if err.filename == path:
595 raise err
597 raise err
596 samestat = getattr(os.path, 'samestat', None)
598 samestat = getattr(os.path, 'samestat', None)
597 if followsym and samestat is not None:
599 if followsym and samestat is not None:
598 def adddir(dirlst, dirname):
600 def adddir(dirlst, dirname):
599 match = False
601 match = False
600 dirstat = os.stat(dirname)
602 dirstat = os.stat(dirname)
601 for lstdirstat in dirlst:
603 for lstdirstat in dirlst:
602 if samestat(dirstat, lstdirstat):
604 if samestat(dirstat, lstdirstat):
603 match = True
605 match = True
604 break
606 break
605 if not match:
607 if not match:
606 dirlst.append(dirstat)
608 dirlst.append(dirstat)
607 return not match
609 return not match
608 else:
610 else:
609 followsym = False
611 followsym = False
610
612
611 if (seen_dirs is None) and followsym:
613 if (seen_dirs is None) and followsym:
612 seen_dirs = []
614 seen_dirs = []
613 adddir(seen_dirs, path)
615 adddir(seen_dirs, path)
614 for root, dirs, files in os.walk(path, topdown=True, onerror=errhandler):
616 for root, dirs, files in os.walk(path, topdown=True, onerror=errhandler):
615 dirs.sort()
617 dirs.sort()
616 if '.hg' in dirs:
618 if '.hg' in dirs:
617 yield root # found a repository
619 yield root # found a repository
618 qroot = os.path.join(root, '.hg', 'patches')
620 qroot = os.path.join(root, '.hg', 'patches')
619 if os.path.isdir(os.path.join(qroot, '.hg')):
621 if os.path.isdir(os.path.join(qroot, '.hg')):
620 yield qroot # we have a patch queue repo here
622 yield qroot # we have a patch queue repo here
621 if recurse:
623 if recurse:
622 # avoid recursing inside the .hg directory
624 # avoid recursing inside the .hg directory
623 dirs.remove('.hg')
625 dirs.remove('.hg')
624 else:
626 else:
625 dirs[:] = [] # don't descend further
627 dirs[:] = [] # don't descend further
626 elif followsym:
628 elif followsym:
627 newdirs = []
629 newdirs = []
628 for d in dirs:
630 for d in dirs:
629 fname = os.path.join(root, d)
631 fname = os.path.join(root, d)
630 if adddir(seen_dirs, fname):
632 if adddir(seen_dirs, fname):
631 if os.path.islink(fname):
633 if os.path.islink(fname):
632 for hgname in walkrepos(fname, True, seen_dirs):
634 for hgname in walkrepos(fname, True, seen_dirs):
633 yield hgname
635 yield hgname
634 else:
636 else:
635 newdirs.append(d)
637 newdirs.append(d)
636 dirs[:] = newdirs
638 dirs[:] = newdirs
637
639
638 def osrcpath():
640 def osrcpath():
639 '''return default os-specific hgrc search path'''
641 '''return default os-specific hgrc search path'''
640 path = []
642 path = []
641 defaultpath = os.path.join(util.datapath, 'default.d')
643 defaultpath = os.path.join(util.datapath, 'default.d')
642 if os.path.isdir(defaultpath):
644 if os.path.isdir(defaultpath):
643 for f, kind in osutil.listdir(defaultpath):
645 for f, kind in osutil.listdir(defaultpath):
644 if f.endswith('.rc'):
646 if f.endswith('.rc'):
645 path.append(os.path.join(defaultpath, f))
647 path.append(os.path.join(defaultpath, f))
646 path.extend(systemrcpath())
648 path.extend(systemrcpath())
647 path.extend(userrcpath())
649 path.extend(userrcpath())
648 path = [os.path.normpath(f) for f in path]
650 path = [os.path.normpath(f) for f in path]
649 return path
651 return path
650
652
651 _rcpath = None
653 _rcpath = None
652
654
653 def rcpath():
655 def rcpath():
654 '''return hgrc search path. if env var HGRCPATH is set, use it.
656 '''return hgrc search path. if env var HGRCPATH is set, use it.
655 for each item in path, if directory, use files ending in .rc,
657 for each item in path, if directory, use files ending in .rc,
656 else use item.
658 else use item.
657 make HGRCPATH empty to only look in .hg/hgrc of current repo.
659 make HGRCPATH empty to only look in .hg/hgrc of current repo.
658 if no HGRCPATH, use default os-specific path.'''
660 if no HGRCPATH, use default os-specific path.'''
659 global _rcpath
661 global _rcpath
660 if _rcpath is None:
662 if _rcpath is None:
661 if 'HGRCPATH' in os.environ:
663 if 'HGRCPATH' in os.environ:
662 _rcpath = []
664 _rcpath = []
663 for p in os.environ['HGRCPATH'].split(os.pathsep):
665 for p in os.environ['HGRCPATH'].split(os.pathsep):
664 if not p:
666 if not p:
665 continue
667 continue
666 p = util.expandpath(p)
668 p = util.expandpath(p)
667 if os.path.isdir(p):
669 if os.path.isdir(p):
668 for f, kind in osutil.listdir(p):
670 for f, kind in osutil.listdir(p):
669 if f.endswith('.rc'):
671 if f.endswith('.rc'):
670 _rcpath.append(os.path.join(p, f))
672 _rcpath.append(os.path.join(p, f))
671 else:
673 else:
672 _rcpath.append(p)
674 _rcpath.append(p)
673 else:
675 else:
674 _rcpath = osrcpath()
676 _rcpath = osrcpath()
675 return _rcpath
677 return _rcpath
676
678
677 def intrev(rev):
679 def intrev(rev):
678 """Return integer for a given revision that can be used in comparison or
680 """Return integer for a given revision that can be used in comparison or
679 arithmetic operation"""
681 arithmetic operation"""
680 if rev is None:
682 if rev is None:
681 return wdirrev
683 return wdirrev
682 return rev
684 return rev
683
685
684 def revsingle(repo, revspec, default='.'):
686 def revsingle(repo, revspec, default='.'):
685 if not revspec and revspec != 0:
687 if not revspec and revspec != 0:
686 return repo[default]
688 return repo[default]
687
689
688 l = revrange(repo, [revspec])
690 l = revrange(repo, [revspec])
689 if not l:
691 if not l:
690 raise util.Abort(_('empty revision set'))
692 raise util.Abort(_('empty revision set'))
691 return repo[l.last()]
693 return repo[l.last()]
692
694
693 def _pairspec(revspec):
695 def _pairspec(revspec):
694 tree = revset.parse(revspec)
696 tree = revset.parse(revspec)
695 tree = revset.optimize(tree, True)[1] # fix up "x^:y" -> "(x^):y"
697 tree = revset.optimize(tree, True)[1] # fix up "x^:y" -> "(x^):y"
696 return tree and tree[0] in ('range', 'rangepre', 'rangepost', 'rangeall')
698 return tree and tree[0] in ('range', 'rangepre', 'rangepost', 'rangeall')
697
699
698 def revpair(repo, revs):
700 def revpair(repo, revs):
699 if not revs:
701 if not revs:
700 return repo.dirstate.p1(), None
702 return repo.dirstate.p1(), None
701
703
702 l = revrange(repo, revs)
704 l = revrange(repo, revs)
703
705
704 if not l:
706 if not l:
705 first = second = None
707 first = second = None
706 elif l.isascending():
708 elif l.isascending():
707 first = l.min()
709 first = l.min()
708 second = l.max()
710 second = l.max()
709 elif l.isdescending():
711 elif l.isdescending():
710 first = l.max()
712 first = l.max()
711 second = l.min()
713 second = l.min()
712 else:
714 else:
713 first = l.first()
715 first = l.first()
714 second = l.last()
716 second = l.last()
715
717
716 if first is None:
718 if first is None:
717 raise util.Abort(_('empty revision range'))
719 raise util.Abort(_('empty revision range'))
718
720
719 # if top-level is range expression, the result must always be a pair
721 # if top-level is range expression, the result must always be a pair
720 if first == second and len(revs) == 1 and not _pairspec(revs[0]):
722 if first == second and len(revs) == 1 and not _pairspec(revs[0]):
721 return repo.lookup(first), None
723 return repo.lookup(first), None
722
724
723 return repo.lookup(first), repo.lookup(second)
725 return repo.lookup(first), repo.lookup(second)
724
726
725 def revrange(repo, revs):
727 def revrange(repo, revs):
726 """Yield revision as strings from a list of revision specifications."""
728 """Yield revision as strings from a list of revision specifications."""
727 allspecs = []
729 allspecs = []
728 for spec in revs:
730 for spec in revs:
729 if isinstance(spec, int):
731 if isinstance(spec, int):
730 spec = revset.formatspec('rev(%d)', spec)
732 spec = revset.formatspec('rev(%d)', spec)
731 allspecs.append(spec)
733 allspecs.append(spec)
732 m = revset.matchany(repo.ui, allspecs, repo)
734 m = revset.matchany(repo.ui, allspecs, repo)
733 return m(repo)
735 return m(repo)
734
736
735 def expandpats(pats):
737 def expandpats(pats):
736 '''Expand bare globs when running on windows.
738 '''Expand bare globs when running on windows.
737 On posix we assume it already has already been done by sh.'''
739 On posix we assume it already has already been done by sh.'''
738 if not util.expandglobs:
740 if not util.expandglobs:
739 return list(pats)
741 return list(pats)
740 ret = []
742 ret = []
741 for kindpat in pats:
743 for kindpat in pats:
742 kind, pat = matchmod._patsplit(kindpat, None)
744 kind, pat = matchmod._patsplit(kindpat, None)
743 if kind is None:
745 if kind is None:
744 try:
746 try:
745 globbed = glob.glob(pat)
747 globbed = glob.glob(pat)
746 except re.error:
748 except re.error:
747 globbed = [pat]
749 globbed = [pat]
748 if globbed:
750 if globbed:
749 ret.extend(globbed)
751 ret.extend(globbed)
750 continue
752 continue
751 ret.append(kindpat)
753 ret.append(kindpat)
752 return ret
754 return ret
753
755
754 def matchandpats(ctx, pats=[], opts={}, globbed=False, default='relpath',
756 def matchandpats(ctx, pats=[], opts={}, globbed=False, default='relpath',
755 badfn=None):
757 badfn=None):
756 '''Return a matcher and the patterns that were used.
758 '''Return a matcher and the patterns that were used.
757 The matcher will warn about bad matches, unless an alternate badfn callback
759 The matcher will warn about bad matches, unless an alternate badfn callback
758 is provided.'''
760 is provided.'''
759 if pats == ("",):
761 if pats == ("",):
760 pats = []
762 pats = []
761 if not globbed and default == 'relpath':
763 if not globbed and default == 'relpath':
762 pats = expandpats(pats or [])
764 pats = expandpats(pats or [])
763
765
764 def bad(f, msg):
766 def bad(f, msg):
765 ctx.repo().ui.warn("%s: %s\n" % (m.rel(f), msg))
767 ctx.repo().ui.warn("%s: %s\n" % (m.rel(f), msg))
766
768
767 if badfn is None:
769 if badfn is None:
768 badfn = bad
770 badfn = bad
769
771
770 m = ctx.match(pats, opts.get('include'), opts.get('exclude'),
772 m = ctx.match(pats, opts.get('include'), opts.get('exclude'),
771 default, listsubrepos=opts.get('subrepos'), badfn=badfn)
773 default, listsubrepos=opts.get('subrepos'), badfn=badfn)
772
774
773 if m.always():
775 if m.always():
774 pats = []
776 pats = []
775 return m, pats
777 return m, pats
776
778
777 def match(ctx, pats=[], opts={}, globbed=False, default='relpath', badfn=None):
779 def match(ctx, pats=[], opts={}, globbed=False, default='relpath', badfn=None):
778 '''Return a matcher that will warn about bad matches.'''
780 '''Return a matcher that will warn about bad matches.'''
779 return matchandpats(ctx, pats, opts, globbed, default, badfn=badfn)[0]
781 return matchandpats(ctx, pats, opts, globbed, default, badfn=badfn)[0]
780
782
781 def matchall(repo):
783 def matchall(repo):
782 '''Return a matcher that will efficiently match everything.'''
784 '''Return a matcher that will efficiently match everything.'''
783 return matchmod.always(repo.root, repo.getcwd())
785 return matchmod.always(repo.root, repo.getcwd())
784
786
785 def matchfiles(repo, files, badfn=None):
787 def matchfiles(repo, files, badfn=None):
786 '''Return a matcher that will efficiently match exactly these files.'''
788 '''Return a matcher that will efficiently match exactly these files.'''
787 return matchmod.exact(repo.root, repo.getcwd(), files, badfn=badfn)
789 return matchmod.exact(repo.root, repo.getcwd(), files, badfn=badfn)
788
790
789 def addremove(repo, matcher, prefix, opts={}, dry_run=None, similarity=None):
791 def addremove(repo, matcher, prefix, opts={}, dry_run=None, similarity=None):
790 m = matcher
792 m = matcher
791 if dry_run is None:
793 if dry_run is None:
792 dry_run = opts.get('dry_run')
794 dry_run = opts.get('dry_run')
793 if similarity is None:
795 if similarity is None:
794 similarity = float(opts.get('similarity') or 0)
796 similarity = float(opts.get('similarity') or 0)
795
797
796 ret = 0
798 ret = 0
797 join = lambda f: os.path.join(prefix, f)
799 join = lambda f: os.path.join(prefix, f)
798
800
799 def matchessubrepo(matcher, subpath):
801 def matchessubrepo(matcher, subpath):
800 if matcher.exact(subpath):
802 if matcher.exact(subpath):
801 return True
803 return True
802 for f in matcher.files():
804 for f in matcher.files():
803 if f.startswith(subpath):
805 if f.startswith(subpath):
804 return True
806 return True
805 return False
807 return False
806
808
807 wctx = repo[None]
809 wctx = repo[None]
808 for subpath in sorted(wctx.substate):
810 for subpath in sorted(wctx.substate):
809 if opts.get('subrepos') or matchessubrepo(m, subpath):
811 if opts.get('subrepos') or matchessubrepo(m, subpath):
810 sub = wctx.sub(subpath)
812 sub = wctx.sub(subpath)
811 try:
813 try:
812 submatch = matchmod.narrowmatcher(subpath, m)
814 submatch = matchmod.narrowmatcher(subpath, m)
813 if sub.addremove(submatch, prefix, opts, dry_run, similarity):
815 if sub.addremove(submatch, prefix, opts, dry_run, similarity):
814 ret = 1
816 ret = 1
815 except error.LookupError:
817 except error.LookupError:
816 repo.ui.status(_("skipping missing subrepository: %s\n")
818 repo.ui.status(_("skipping missing subrepository: %s\n")
817 % join(subpath))
819 % join(subpath))
818
820
819 rejected = []
821 rejected = []
820 def badfn(f, msg):
822 def badfn(f, msg):
821 if f in m.files():
823 if f in m.files():
822 m.bad(f, msg)
824 m.bad(f, msg)
823 rejected.append(f)
825 rejected.append(f)
824
826
825 badmatch = matchmod.badmatch(m, badfn)
827 badmatch = matchmod.badmatch(m, badfn)
826 added, unknown, deleted, removed, forgotten = _interestingfiles(repo,
828 added, unknown, deleted, removed, forgotten = _interestingfiles(repo,
827 badmatch)
829 badmatch)
828
830
829 unknownset = set(unknown + forgotten)
831 unknownset = set(unknown + forgotten)
830 toprint = unknownset.copy()
832 toprint = unknownset.copy()
831 toprint.update(deleted)
833 toprint.update(deleted)
832 for abs in sorted(toprint):
834 for abs in sorted(toprint):
833 if repo.ui.verbose or not m.exact(abs):
835 if repo.ui.verbose or not m.exact(abs):
834 if abs in unknownset:
836 if abs in unknownset:
835 status = _('adding %s\n') % m.uipath(abs)
837 status = _('adding %s\n') % m.uipath(abs)
836 else:
838 else:
837 status = _('removing %s\n') % m.uipath(abs)
839 status = _('removing %s\n') % m.uipath(abs)
838 repo.ui.status(status)
840 repo.ui.status(status)
839
841
840 renames = _findrenames(repo, m, added + unknown, removed + deleted,
842 renames = _findrenames(repo, m, added + unknown, removed + deleted,
841 similarity)
843 similarity)
842
844
843 if not dry_run:
845 if not dry_run:
844 _markchanges(repo, unknown + forgotten, deleted, renames)
846 _markchanges(repo, unknown + forgotten, deleted, renames)
845
847
846 for f in rejected:
848 for f in rejected:
847 if f in m.files():
849 if f in m.files():
848 return 1
850 return 1
849 return ret
851 return ret
850
852
851 def marktouched(repo, files, similarity=0.0):
853 def marktouched(repo, files, similarity=0.0):
852 '''Assert that files have somehow been operated upon. files are relative to
854 '''Assert that files have somehow been operated upon. files are relative to
853 the repo root.'''
855 the repo root.'''
854 m = matchfiles(repo, files, badfn=lambda x, y: rejected.append(x))
856 m = matchfiles(repo, files, badfn=lambda x, y: rejected.append(x))
855 rejected = []
857 rejected = []
856
858
857 added, unknown, deleted, removed, forgotten = _interestingfiles(repo, m)
859 added, unknown, deleted, removed, forgotten = _interestingfiles(repo, m)
858
860
859 if repo.ui.verbose:
861 if repo.ui.verbose:
860 unknownset = set(unknown + forgotten)
862 unknownset = set(unknown + forgotten)
861 toprint = unknownset.copy()
863 toprint = unknownset.copy()
862 toprint.update(deleted)
864 toprint.update(deleted)
863 for abs in sorted(toprint):
865 for abs in sorted(toprint):
864 if abs in unknownset:
866 if abs in unknownset:
865 status = _('adding %s\n') % abs
867 status = _('adding %s\n') % abs
866 else:
868 else:
867 status = _('removing %s\n') % abs
869 status = _('removing %s\n') % abs
868 repo.ui.status(status)
870 repo.ui.status(status)
869
871
870 renames = _findrenames(repo, m, added + unknown, removed + deleted,
872 renames = _findrenames(repo, m, added + unknown, removed + deleted,
871 similarity)
873 similarity)
872
874
873 _markchanges(repo, unknown + forgotten, deleted, renames)
875 _markchanges(repo, unknown + forgotten, deleted, renames)
874
876
875 for f in rejected:
877 for f in rejected:
876 if f in m.files():
878 if f in m.files():
877 return 1
879 return 1
878 return 0
880 return 0
879
881
880 def _interestingfiles(repo, matcher):
882 def _interestingfiles(repo, matcher):
881 '''Walk dirstate with matcher, looking for files that addremove would care
883 '''Walk dirstate with matcher, looking for files that addremove would care
882 about.
884 about.
883
885
884 This is different from dirstate.status because it doesn't care about
886 This is different from dirstate.status because it doesn't care about
885 whether files are modified or clean.'''
887 whether files are modified or clean.'''
886 added, unknown, deleted, removed, forgotten = [], [], [], [], []
888 added, unknown, deleted, removed, forgotten = [], [], [], [], []
887 audit_path = pathutil.pathauditor(repo.root)
889 audit_path = pathutil.pathauditor(repo.root)
888
890
889 ctx = repo[None]
891 ctx = repo[None]
890 dirstate = repo.dirstate
892 dirstate = repo.dirstate
891 walkresults = dirstate.walk(matcher, sorted(ctx.substate), True, False,
893 walkresults = dirstate.walk(matcher, sorted(ctx.substate), True, False,
892 full=False)
894 full=False)
893 for abs, st in walkresults.iteritems():
895 for abs, st in walkresults.iteritems():
894 dstate = dirstate[abs]
896 dstate = dirstate[abs]
895 if dstate == '?' and audit_path.check(abs):
897 if dstate == '?' and audit_path.check(abs):
896 unknown.append(abs)
898 unknown.append(abs)
897 elif dstate != 'r' and not st:
899 elif dstate != 'r' and not st:
898 deleted.append(abs)
900 deleted.append(abs)
899 elif dstate == 'r' and st:
901 elif dstate == 'r' and st:
900 forgotten.append(abs)
902 forgotten.append(abs)
901 # for finding renames
903 # for finding renames
902 elif dstate == 'r' and not st:
904 elif dstate == 'r' and not st:
903 removed.append(abs)
905 removed.append(abs)
904 elif dstate == 'a':
906 elif dstate == 'a':
905 added.append(abs)
907 added.append(abs)
906
908
907 return added, unknown, deleted, removed, forgotten
909 return added, unknown, deleted, removed, forgotten
908
910
909 def _findrenames(repo, matcher, added, removed, similarity):
911 def _findrenames(repo, matcher, added, removed, similarity):
910 '''Find renames from removed files to added ones.'''
912 '''Find renames from removed files to added ones.'''
911 renames = {}
913 renames = {}
912 if similarity > 0:
914 if similarity > 0:
913 for old, new, score in similar.findrenames(repo, added, removed,
915 for old, new, score in similar.findrenames(repo, added, removed,
914 similarity):
916 similarity):
915 if (repo.ui.verbose or not matcher.exact(old)
917 if (repo.ui.verbose or not matcher.exact(old)
916 or not matcher.exact(new)):
918 or not matcher.exact(new)):
917 repo.ui.status(_('recording removal of %s as rename to %s '
919 repo.ui.status(_('recording removal of %s as rename to %s '
918 '(%d%% similar)\n') %
920 '(%d%% similar)\n') %
919 (matcher.rel(old), matcher.rel(new),
921 (matcher.rel(old), matcher.rel(new),
920 score * 100))
922 score * 100))
921 renames[new] = old
923 renames[new] = old
922 return renames
924 return renames
923
925
924 def _markchanges(repo, unknown, deleted, renames):
926 def _markchanges(repo, unknown, deleted, renames):
925 '''Marks the files in unknown as added, the files in deleted as removed,
927 '''Marks the files in unknown as added, the files in deleted as removed,
926 and the files in renames as copied.'''
928 and the files in renames as copied.'''
927 wctx = repo[None]
929 wctx = repo[None]
928 wlock = repo.wlock()
930 wlock = repo.wlock()
929 try:
931 try:
930 wctx.forget(deleted)
932 wctx.forget(deleted)
931 wctx.add(unknown)
933 wctx.add(unknown)
932 for new, old in renames.iteritems():
934 for new, old in renames.iteritems():
933 wctx.copy(old, new)
935 wctx.copy(old, new)
934 finally:
936 finally:
935 wlock.release()
937 wlock.release()
936
938
937 def dirstatecopy(ui, repo, wctx, src, dst, dryrun=False, cwd=None):
939 def dirstatecopy(ui, repo, wctx, src, dst, dryrun=False, cwd=None):
938 """Update the dirstate to reflect the intent of copying src to dst. For
940 """Update the dirstate to reflect the intent of copying src to dst. For
939 different reasons it might not end with dst being marked as copied from src.
941 different reasons it might not end with dst being marked as copied from src.
940 """
942 """
941 origsrc = repo.dirstate.copied(src) or src
943 origsrc = repo.dirstate.copied(src) or src
942 if dst == origsrc: # copying back a copy?
944 if dst == origsrc: # copying back a copy?
943 if repo.dirstate[dst] not in 'mn' and not dryrun:
945 if repo.dirstate[dst] not in 'mn' and not dryrun:
944 repo.dirstate.normallookup(dst)
946 repo.dirstate.normallookup(dst)
945 else:
947 else:
946 if repo.dirstate[origsrc] == 'a' and origsrc == src:
948 if repo.dirstate[origsrc] == 'a' and origsrc == src:
947 if not ui.quiet:
949 if not ui.quiet:
948 ui.warn(_("%s has not been committed yet, so no copy "
950 ui.warn(_("%s has not been committed yet, so no copy "
949 "data will be stored for %s.\n")
951 "data will be stored for %s.\n")
950 % (repo.pathto(origsrc, cwd), repo.pathto(dst, cwd)))
952 % (repo.pathto(origsrc, cwd), repo.pathto(dst, cwd)))
951 if repo.dirstate[dst] in '?r' and not dryrun:
953 if repo.dirstate[dst] in '?r' and not dryrun:
952 wctx.add([dst])
954 wctx.add([dst])
953 elif not dryrun:
955 elif not dryrun:
954 wctx.copy(origsrc, dst)
956 wctx.copy(origsrc, dst)
955
957
956 def readrequires(opener, supported):
958 def readrequires(opener, supported):
957 '''Reads and parses .hg/requires and checks if all entries found
959 '''Reads and parses .hg/requires and checks if all entries found
958 are in the list of supported features.'''
960 are in the list of supported features.'''
959 requirements = set(opener.read("requires").splitlines())
961 requirements = set(opener.read("requires").splitlines())
960 missings = []
962 missings = []
961 for r in requirements:
963 for r in requirements:
962 if r not in supported:
964 if r not in supported:
963 if not r or not r[0].isalnum():
965 if not r or not r[0].isalnum():
964 raise error.RequirementError(_(".hg/requires file is corrupt"))
966 raise error.RequirementError(_(".hg/requires file is corrupt"))
965 missings.append(r)
967 missings.append(r)
966 missings.sort()
968 missings.sort()
967 if missings:
969 if missings:
968 raise error.RequirementError(
970 raise error.RequirementError(
969 _("repository requires features unknown to this Mercurial: %s")
971 _("repository requires features unknown to this Mercurial: %s")
970 % " ".join(missings),
972 % " ".join(missings),
971 hint=_("see http://mercurial.selenic.com/wiki/MissingRequirement"
973 hint=_("see http://mercurial.selenic.com/wiki/MissingRequirement"
972 " for more information"))
974 " for more information"))
973 return requirements
975 return requirements
974
976
975 def writerequires(opener, requirements):
977 def writerequires(opener, requirements):
976 reqfile = opener("requires", "w")
978 reqfile = opener("requires", "w")
977 for r in sorted(requirements):
979 for r in sorted(requirements):
978 reqfile.write("%s\n" % r)
980 reqfile.write("%s\n" % r)
979 reqfile.close()
981 reqfile.close()
980
982
981 class filecachesubentry(object):
983 class filecachesubentry(object):
982 def __init__(self, path, stat):
984 def __init__(self, path, stat):
983 self.path = path
985 self.path = path
984 self.cachestat = None
986 self.cachestat = None
985 self._cacheable = None
987 self._cacheable = None
986
988
987 if stat:
989 if stat:
988 self.cachestat = filecachesubentry.stat(self.path)
990 self.cachestat = filecachesubentry.stat(self.path)
989
991
990 if self.cachestat:
992 if self.cachestat:
991 self._cacheable = self.cachestat.cacheable()
993 self._cacheable = self.cachestat.cacheable()
992 else:
994 else:
993 # None means we don't know yet
995 # None means we don't know yet
994 self._cacheable = None
996 self._cacheable = None
995
997
996 def refresh(self):
998 def refresh(self):
997 if self.cacheable():
999 if self.cacheable():
998 self.cachestat = filecachesubentry.stat(self.path)
1000 self.cachestat = filecachesubentry.stat(self.path)
999
1001
1000 def cacheable(self):
1002 def cacheable(self):
1001 if self._cacheable is not None:
1003 if self._cacheable is not None:
1002 return self._cacheable
1004 return self._cacheable
1003
1005
1004 # we don't know yet, assume it is for now
1006 # we don't know yet, assume it is for now
1005 return True
1007 return True
1006
1008
1007 def changed(self):
1009 def changed(self):
1008 # no point in going further if we can't cache it
1010 # no point in going further if we can't cache it
1009 if not self.cacheable():
1011 if not self.cacheable():
1010 return True
1012 return True
1011
1013
1012 newstat = filecachesubentry.stat(self.path)
1014 newstat = filecachesubentry.stat(self.path)
1013
1015
1014 # we may not know if it's cacheable yet, check again now
1016 # we may not know if it's cacheable yet, check again now
1015 if newstat and self._cacheable is None:
1017 if newstat and self._cacheable is None:
1016 self._cacheable = newstat.cacheable()
1018 self._cacheable = newstat.cacheable()
1017
1019
1018 # check again
1020 # check again
1019 if not self._cacheable:
1021 if not self._cacheable:
1020 return True
1022 return True
1021
1023
1022 if self.cachestat != newstat:
1024 if self.cachestat != newstat:
1023 self.cachestat = newstat
1025 self.cachestat = newstat
1024 return True
1026 return True
1025 else:
1027 else:
1026 return False
1028 return False
1027
1029
1028 @staticmethod
1030 @staticmethod
1029 def stat(path):
1031 def stat(path):
1030 try:
1032 try:
1031 return util.cachestat(path)
1033 return util.cachestat(path)
1032 except OSError as e:
1034 except OSError as e:
1033 if e.errno != errno.ENOENT:
1035 if e.errno != errno.ENOENT:
1034 raise
1036 raise
1035
1037
1036 class filecacheentry(object):
1038 class filecacheentry(object):
1037 def __init__(self, paths, stat=True):
1039 def __init__(self, paths, stat=True):
1038 self._entries = []
1040 self._entries = []
1039 for path in paths:
1041 for path in paths:
1040 self._entries.append(filecachesubentry(path, stat))
1042 self._entries.append(filecachesubentry(path, stat))
1041
1043
1042 def changed(self):
1044 def changed(self):
1043 '''true if any entry has changed'''
1045 '''true if any entry has changed'''
1044 for entry in self._entries:
1046 for entry in self._entries:
1045 if entry.changed():
1047 if entry.changed():
1046 return True
1048 return True
1047 return False
1049 return False
1048
1050
1049 def refresh(self):
1051 def refresh(self):
1050 for entry in self._entries:
1052 for entry in self._entries:
1051 entry.refresh()
1053 entry.refresh()
1052
1054
1053 class filecache(object):
1055 class filecache(object):
1054 '''A property like decorator that tracks files under .hg/ for updates.
1056 '''A property like decorator that tracks files under .hg/ for updates.
1055
1057
1056 Records stat info when called in _filecache.
1058 Records stat info when called in _filecache.
1057
1059
1058 On subsequent calls, compares old stat info with new info, and recreates the
1060 On subsequent calls, compares old stat info with new info, and recreates the
1059 object when any of the files changes, updating the new stat info in
1061 object when any of the files changes, updating the new stat info in
1060 _filecache.
1062 _filecache.
1061
1063
1062 Mercurial either atomic renames or appends for files under .hg,
1064 Mercurial either atomic renames or appends for files under .hg,
1063 so to ensure the cache is reliable we need the filesystem to be able
1065 so to ensure the cache is reliable we need the filesystem to be able
1064 to tell us if a file has been replaced. If it can't, we fallback to
1066 to tell us if a file has been replaced. If it can't, we fallback to
1065 recreating the object on every call (essentially the same behavior as
1067 recreating the object on every call (essentially the same behavior as
1066 propertycache).
1068 propertycache).
1067
1069
1068 '''
1070 '''
1069 def __init__(self, *paths):
1071 def __init__(self, *paths):
1070 self.paths = paths
1072 self.paths = paths
1071
1073
1072 def join(self, obj, fname):
1074 def join(self, obj, fname):
1073 """Used to compute the runtime path of a cached file.
1075 """Used to compute the runtime path of a cached file.
1074
1076
1075 Users should subclass filecache and provide their own version of this
1077 Users should subclass filecache and provide their own version of this
1076 function to call the appropriate join function on 'obj' (an instance
1078 function to call the appropriate join function on 'obj' (an instance
1077 of the class that its member function was decorated).
1079 of the class that its member function was decorated).
1078 """
1080 """
1079 return obj.join(fname)
1081 return obj.join(fname)
1080
1082
1081 def __call__(self, func):
1083 def __call__(self, func):
1082 self.func = func
1084 self.func = func
1083 self.name = func.__name__
1085 self.name = func.__name__
1084 return self
1086 return self
1085
1087
1086 def __get__(self, obj, type=None):
1088 def __get__(self, obj, type=None):
1087 # do we need to check if the file changed?
1089 # do we need to check if the file changed?
1088 if self.name in obj.__dict__:
1090 if self.name in obj.__dict__:
1089 assert self.name in obj._filecache, self.name
1091 assert self.name in obj._filecache, self.name
1090 return obj.__dict__[self.name]
1092 return obj.__dict__[self.name]
1091
1093
1092 entry = obj._filecache.get(self.name)
1094 entry = obj._filecache.get(self.name)
1093
1095
1094 if entry:
1096 if entry:
1095 if entry.changed():
1097 if entry.changed():
1096 entry.obj = self.func(obj)
1098 entry.obj = self.func(obj)
1097 else:
1099 else:
1098 paths = [self.join(obj, path) for path in self.paths]
1100 paths = [self.join(obj, path) for path in self.paths]
1099
1101
1100 # We stat -before- creating the object so our cache doesn't lie if
1102 # We stat -before- creating the object so our cache doesn't lie if
1101 # a writer modified between the time we read and stat
1103 # a writer modified between the time we read and stat
1102 entry = filecacheentry(paths, True)
1104 entry = filecacheentry(paths, True)
1103 entry.obj = self.func(obj)
1105 entry.obj = self.func(obj)
1104
1106
1105 obj._filecache[self.name] = entry
1107 obj._filecache[self.name] = entry
1106
1108
1107 obj.__dict__[self.name] = entry.obj
1109 obj.__dict__[self.name] = entry.obj
1108 return entry.obj
1110 return entry.obj
1109
1111
1110 def __set__(self, obj, value):
1112 def __set__(self, obj, value):
1111 if self.name not in obj._filecache:
1113 if self.name not in obj._filecache:
1112 # we add an entry for the missing value because X in __dict__
1114 # we add an entry for the missing value because X in __dict__
1113 # implies X in _filecache
1115 # implies X in _filecache
1114 paths = [self.join(obj, path) for path in self.paths]
1116 paths = [self.join(obj, path) for path in self.paths]
1115 ce = filecacheentry(paths, False)
1117 ce = filecacheentry(paths, False)
1116 obj._filecache[self.name] = ce
1118 obj._filecache[self.name] = ce
1117 else:
1119 else:
1118 ce = obj._filecache[self.name]
1120 ce = obj._filecache[self.name]
1119
1121
1120 ce.obj = value # update cached copy
1122 ce.obj = value # update cached copy
1121 obj.__dict__[self.name] = value # update copy returned by obj.x
1123 obj.__dict__[self.name] = value # update copy returned by obj.x
1122
1124
1123 def __delete__(self, obj):
1125 def __delete__(self, obj):
1124 try:
1126 try:
1125 del obj.__dict__[self.name]
1127 del obj.__dict__[self.name]
1126 except KeyError:
1128 except KeyError:
1127 raise AttributeError(self.name)
1129 raise AttributeError(self.name)
General Comments 0
You need to be logged in to leave comments. Login now