##// END OF EJS Templates
largefile: status is buggy on repoproxy, so run unfiltered...
Pierre-Yves David -
r18012:848c428b default
parent child Browse files
Show More
@@ -1,1126 +1,1129 b''
1 1 # Copyright 2009-2010 Gregory P. Ward
2 2 # Copyright 2009-2010 Intelerad Medical Systems Incorporated
3 3 # Copyright 2010-2011 Fog Creek Software
4 4 # Copyright 2010-2011 Unity Technologies
5 5 #
6 6 # This software may be used and distributed according to the terms of the
7 7 # GNU General Public License version 2 or any later version.
8 8
9 9 '''Overridden Mercurial commands and functions for the largefiles extension'''
10 10
11 11 import os
12 12 import copy
13 13
14 14 from mercurial import hg, commands, util, cmdutil, scmutil, match as match_, \
15 15 node, archival, error, merge
16 16 from mercurial.i18n import _
17 17 from mercurial.node import hex
18 18 from hgext import rebase
19 19
20 20 import lfutil
21 21 import lfcommands
22 22
23 23 # -- Utility functions: commonly/repeatedly needed functionality ---------------
24 24
25 25 def installnormalfilesmatchfn(manifest):
26 26 '''overrides scmutil.match so that the matcher it returns will ignore all
27 27 largefiles'''
28 28 oldmatch = None # for the closure
29 29 def overridematch(ctx, pats=[], opts={}, globbed=False,
30 30 default='relpath'):
31 31 match = oldmatch(ctx, pats, opts, globbed, default)
32 32 m = copy.copy(match)
33 33 notlfile = lambda f: not (lfutil.isstandin(f) or lfutil.standin(f) in
34 34 manifest)
35 35 m._files = filter(notlfile, m._files)
36 36 m._fmap = set(m._files)
37 37 origmatchfn = m.matchfn
38 38 m.matchfn = lambda f: notlfile(f) and origmatchfn(f) or None
39 39 return m
40 40 oldmatch = installmatchfn(overridematch)
41 41
42 42 def installmatchfn(f):
43 43 oldmatch = scmutil.match
44 44 setattr(f, 'oldmatch', oldmatch)
45 45 scmutil.match = f
46 46 return oldmatch
47 47
48 48 def restorematchfn():
49 49 '''restores scmutil.match to what it was before installnormalfilesmatchfn
50 50 was called. no-op if scmutil.match is its original function.
51 51
52 52 Note that n calls to installnormalfilesmatchfn will require n calls to
53 53 restore matchfn to reverse'''
54 54 scmutil.match = getattr(scmutil.match, 'oldmatch', scmutil.match)
55 55
56 56 def addlargefiles(ui, repo, *pats, **opts):
57 57 large = opts.pop('large', None)
58 58 lfsize = lfutil.getminsize(
59 59 ui, lfutil.islfilesrepo(repo), opts.pop('lfsize', None))
60 60
61 61 lfmatcher = None
62 62 if lfutil.islfilesrepo(repo):
63 63 lfpats = ui.configlist(lfutil.longname, 'patterns', default=[])
64 64 if lfpats:
65 65 lfmatcher = match_.match(repo.root, '', list(lfpats))
66 66
67 67 lfnames = []
68 68 m = scmutil.match(repo[None], pats, opts)
69 69 m.bad = lambda x, y: None
70 70 wctx = repo[None]
71 71 for f in repo.walk(m):
72 72 exact = m.exact(f)
73 73 lfile = lfutil.standin(f) in wctx
74 74 nfile = f in wctx
75 75 exists = lfile or nfile
76 76
77 77 # Don't warn the user when they attempt to add a normal tracked file.
78 78 # The normal add code will do that for us.
79 79 if exact and exists:
80 80 if lfile:
81 81 ui.warn(_('%s already a largefile\n') % f)
82 82 continue
83 83
84 84 if (exact or not exists) and not lfutil.isstandin(f):
85 85 wfile = repo.wjoin(f)
86 86
87 87 # In case the file was removed previously, but not committed
88 88 # (issue3507)
89 89 if not os.path.exists(wfile):
90 90 continue
91 91
92 92 abovemin = (lfsize and
93 93 os.lstat(wfile).st_size >= lfsize * 1024 * 1024)
94 94 if large or abovemin or (lfmatcher and lfmatcher(f)):
95 95 lfnames.append(f)
96 96 if ui.verbose or not exact:
97 97 ui.status(_('adding %s as a largefile\n') % m.rel(f))
98 98
99 99 bad = []
100 100 standins = []
101 101
102 102 # Need to lock, otherwise there could be a race condition between
103 103 # when standins are created and added to the repo.
104 104 wlock = repo.wlock()
105 105 try:
106 106 if not opts.get('dry_run'):
107 107 lfdirstate = lfutil.openlfdirstate(ui, repo)
108 108 for f in lfnames:
109 109 standinname = lfutil.standin(f)
110 110 lfutil.writestandin(repo, standinname, hash='',
111 111 executable=lfutil.getexecutable(repo.wjoin(f)))
112 112 standins.append(standinname)
113 113 if lfdirstate[f] == 'r':
114 114 lfdirstate.normallookup(f)
115 115 else:
116 116 lfdirstate.add(f)
117 117 lfdirstate.write()
118 118 bad += [lfutil.splitstandin(f)
119 119 for f in lfutil.repoadd(repo, standins)
120 120 if f in m.files()]
121 121 finally:
122 122 wlock.release()
123 123 return bad
124 124
125 125 def removelargefiles(ui, repo, *pats, **opts):
126 126 after = opts.get('after')
127 127 if not pats and not after:
128 128 raise util.Abort(_('no files specified'))
129 129 m = scmutil.match(repo[None], pats, opts)
130 130 try:
131 131 repo.lfstatus = True
132 132 s = repo.status(match=m, clean=True)
133 133 finally:
134 134 repo.lfstatus = False
135 135 manifest = repo[None].manifest()
136 136 modified, added, deleted, clean = [[f for f in list
137 137 if lfutil.standin(f) in manifest]
138 138 for list in [s[0], s[1], s[3], s[6]]]
139 139
140 140 def warn(files, reason):
141 141 for f in files:
142 142 ui.warn(_('not removing %s: %s (use forget to undo)\n')
143 143 % (m.rel(f), reason))
144 144 return int(len(files) > 0)
145 145
146 146 result = 0
147 147
148 148 if after:
149 149 remove, forget = deleted, []
150 150 result = warn(modified + added + clean, _('file still exists'))
151 151 else:
152 152 remove, forget = deleted + clean, []
153 153 result = warn(modified, _('file is modified'))
154 154 result = warn(added, _('file has been marked for add')) or result
155 155
156 156 for f in sorted(remove + forget):
157 157 if ui.verbose or not m.exact(f):
158 158 ui.status(_('removing %s\n') % m.rel(f))
159 159
160 160 # Need to lock because standin files are deleted then removed from the
161 161 # repository and we could race in-between.
162 162 wlock = repo.wlock()
163 163 try:
164 164 lfdirstate = lfutil.openlfdirstate(ui, repo)
165 165 for f in remove:
166 166 if not after:
167 167 # If this is being called by addremove, notify the user that we
168 168 # are removing the file.
169 169 if getattr(repo, "_isaddremove", False):
170 170 ui.status(_('removing %s\n') % f)
171 171 if os.path.exists(repo.wjoin(f)):
172 172 util.unlinkpath(repo.wjoin(f))
173 173 lfdirstate.remove(f)
174 174 lfdirstate.write()
175 175 forget = [lfutil.standin(f) for f in forget]
176 176 remove = [lfutil.standin(f) for f in remove]
177 177 lfutil.repoforget(repo, forget)
178 178 # If this is being called by addremove, let the original addremove
179 179 # function handle this.
180 180 if not getattr(repo, "_isaddremove", False):
181 181 lfutil.reporemove(repo, remove, unlink=True)
182 182 else:
183 183 lfutil.reporemove(repo, remove, unlink=False)
184 184 finally:
185 185 wlock.release()
186 186
187 187 return result
188 188
189 189 # For overriding mercurial.hgweb.webcommands so that largefiles will
190 190 # appear at their right place in the manifests.
191 191 def decodepath(orig, path):
192 192 return lfutil.splitstandin(path) or path
193 193
194 194 # -- Wrappers: modify existing commands --------------------------------
195 195
196 196 # Add works by going through the files that the user wanted to add and
197 197 # checking if they should be added as largefiles. Then it makes a new
198 198 # matcher which matches only the normal files and runs the original
199 199 # version of add.
200 200 def overrideadd(orig, ui, repo, *pats, **opts):
201 201 normal = opts.pop('normal')
202 202 if normal:
203 203 if opts.get('large'):
204 204 raise util.Abort(_('--normal cannot be used with --large'))
205 205 return orig(ui, repo, *pats, **opts)
206 206 bad = addlargefiles(ui, repo, *pats, **opts)
207 207 installnormalfilesmatchfn(repo[None].manifest())
208 208 result = orig(ui, repo, *pats, **opts)
209 209 restorematchfn()
210 210
211 211 return (result == 1 or bad) and 1 or 0
212 212
213 213 def overrideremove(orig, ui, repo, *pats, **opts):
214 214 installnormalfilesmatchfn(repo[None].manifest())
215 215 result = orig(ui, repo, *pats, **opts)
216 216 restorematchfn()
217 217 return removelargefiles(ui, repo, *pats, **opts) or result
218 218
219 219 def overridestatusfn(orig, repo, rev2, **opts):
220 220 try:
221 221 repo._repo.lfstatus = True
222 222 return orig(repo, rev2, **opts)
223 223 finally:
224 224 repo._repo.lfstatus = False
225 225
226 226 def overridestatus(orig, ui, repo, *pats, **opts):
227 227 try:
228 228 repo.lfstatus = True
229 229 return orig(ui, repo, *pats, **opts)
230 230 finally:
231 231 repo.lfstatus = False
232 232
233 233 def overridedirty(orig, repo, ignoreupdate=False):
234 234 try:
235 235 repo._repo.lfstatus = True
236 236 return orig(repo, ignoreupdate)
237 237 finally:
238 238 repo._repo.lfstatus = False
239 239
240 240 def overridelog(orig, ui, repo, *pats, **opts):
241 241 try:
242 242 repo.lfstatus = True
243 243 return orig(ui, repo, *pats, **opts)
244 244 finally:
245 245 repo.lfstatus = False
246 246
247 247 def overrideverify(orig, ui, repo, *pats, **opts):
248 248 large = opts.pop('large', False)
249 249 all = opts.pop('lfa', False)
250 250 contents = opts.pop('lfc', False)
251 251
252 252 result = orig(ui, repo, *pats, **opts)
253 253 if large:
254 254 result = result or lfcommands.verifylfiles(ui, repo, all, contents)
255 255 return result
256 256
257 257 # Override needs to refresh standins so that update's normal merge
258 258 # will go through properly. Then the other update hook (overriding repo.update)
259 259 # will get the new files. Filemerge is also overridden so that the merge
260 260 # will merge standins correctly.
261 261 def overrideupdate(orig, ui, repo, *pats, **opts):
262 262 lfdirstate = lfutil.openlfdirstate(ui, repo)
263 263 s = lfdirstate.status(match_.always(repo.root, repo.getcwd()), [], False,
264 264 False, False)
265 265 (unsure, modified, added, removed, missing, unknown, ignored, clean) = s
266 266
267 267 # Need to lock between the standins getting updated and their
268 268 # largefiles getting updated
269 269 wlock = repo.wlock()
270 270 try:
271 271 if opts['check']:
272 272 mod = len(modified) > 0
273 273 for lfile in unsure:
274 274 standin = lfutil.standin(lfile)
275 275 if repo['.'][standin].data().strip() != \
276 276 lfutil.hashfile(repo.wjoin(lfile)):
277 277 mod = True
278 278 else:
279 279 lfdirstate.normal(lfile)
280 280 lfdirstate.write()
281 281 if mod:
282 282 raise util.Abort(_('uncommitted local changes'))
283 283 # XXX handle removed differently
284 284 if not opts['clean']:
285 285 for lfile in unsure + modified + added:
286 286 lfutil.updatestandin(repo, lfutil.standin(lfile))
287 287 finally:
288 288 wlock.release()
289 289 return orig(ui, repo, *pats, **opts)
290 290
291 291 # Before starting the manifest merge, merge.updates will call
292 292 # _checkunknown to check if there are any files in the merged-in
293 293 # changeset that collide with unknown files in the working copy.
294 294 #
295 295 # The largefiles are seen as unknown, so this prevents us from merging
296 296 # in a file 'foo' if we already have a largefile with the same name.
297 297 #
298 298 # The overridden function filters the unknown files by removing any
299 299 # largefiles. This makes the merge proceed and we can then handle this
300 300 # case further in the overridden manifestmerge function below.
301 301 def overridecheckunknownfile(origfn, repo, wctx, mctx, f):
302 302 if lfutil.standin(f) in wctx:
303 303 return False
304 304 return origfn(repo, wctx, mctx, f)
305 305
306 306 # The manifest merge handles conflicts on the manifest level. We want
307 307 # to handle changes in largefile-ness of files at this level too.
308 308 #
309 309 # The strategy is to run the original manifestmerge and then process
310 310 # the action list it outputs. There are two cases we need to deal with:
311 311 #
312 312 # 1. Normal file in p1, largefile in p2. Here the largefile is
313 313 # detected via its standin file, which will enter the working copy
314 314 # with a "get" action. It is not "merge" since the standin is all
315 315 # Mercurial is concerned with at this level -- the link to the
316 316 # existing normal file is not relevant here.
317 317 #
318 318 # 2. Largefile in p1, normal file in p2. Here we get a "merge" action
319 319 # since the largefile will be present in the working copy and
320 320 # different from the normal file in p2. Mercurial therefore
321 321 # triggers a merge action.
322 322 #
323 323 # In both cases, we prompt the user and emit new actions to either
324 324 # remove the standin (if the normal file was kept) or to remove the
325 325 # normal file and get the standin (if the largefile was kept). The
326 326 # default prompt answer is to use the largefile version since it was
327 327 # presumably changed on purpose.
328 328 #
329 329 # Finally, the merge.applyupdates function will then take care of
330 330 # writing the files into the working copy and lfcommands.updatelfiles
331 331 # will update the largefiles.
332 332 def overridemanifestmerge(origfn, repo, p1, p2, pa, overwrite, partial):
333 333 actions = origfn(repo, p1, p2, pa, overwrite, partial)
334 334 processed = []
335 335
336 336 for action in actions:
337 337 if overwrite:
338 338 processed.append(action)
339 339 continue
340 340 f, m = action[:2]
341 341
342 342 choices = (_('&Largefile'), _('&Normal file'))
343 343 if m == "g" and lfutil.splitstandin(f) in p1 and f in p2:
344 344 # Case 1: normal file in the working copy, largefile in
345 345 # the second parent
346 346 lfile = lfutil.splitstandin(f)
347 347 standin = f
348 348 msg = _('%s has been turned into a largefile\n'
349 349 'use (l)argefile or keep as (n)ormal file?') % lfile
350 350 if repo.ui.promptchoice(msg, choices, 0) == 0:
351 351 processed.append((lfile, "r"))
352 352 processed.append((standin, "g", p2.flags(standin)))
353 353 else:
354 354 processed.append((standin, "r"))
355 355 elif m == "g" and lfutil.standin(f) in p1 and f in p2:
356 356 # Case 2: largefile in the working copy, normal file in
357 357 # the second parent
358 358 standin = lfutil.standin(f)
359 359 lfile = f
360 360 msg = _('%s has been turned into a normal file\n'
361 361 'keep as (l)argefile or use (n)ormal file?') % lfile
362 362 if repo.ui.promptchoice(msg, choices, 0) == 0:
363 363 processed.append((lfile, "r"))
364 364 else:
365 365 processed.append((standin, "r"))
366 366 processed.append((lfile, "g", p2.flags(lfile)))
367 367 else:
368 368 processed.append(action)
369 369
370 370 return processed
371 371
372 372 # Override filemerge to prompt the user about how they wish to merge
373 373 # largefiles. This will handle identical edits, and copy/rename +
374 374 # edit without prompting the user.
375 375 def overridefilemerge(origfn, repo, mynode, orig, fcd, fco, fca):
376 376 # Use better variable names here. Because this is a wrapper we cannot
377 377 # change the variable names in the function declaration.
378 378 fcdest, fcother, fcancestor = fcd, fco, fca
379 379 if not lfutil.isstandin(orig):
380 380 return origfn(repo, mynode, orig, fcdest, fcother, fcancestor)
381 381 else:
382 382 if not fcother.cmp(fcdest): # files identical?
383 383 return None
384 384
385 385 # backwards, use working dir parent as ancestor
386 386 if fcancestor == fcother:
387 387 fcancestor = fcdest.parents()[0]
388 388
389 389 if orig != fcother.path():
390 390 repo.ui.status(_('merging %s and %s to %s\n')
391 391 % (lfutil.splitstandin(orig),
392 392 lfutil.splitstandin(fcother.path()),
393 393 lfutil.splitstandin(fcdest.path())))
394 394 else:
395 395 repo.ui.status(_('merging %s\n')
396 396 % lfutil.splitstandin(fcdest.path()))
397 397
398 398 if fcancestor.path() != fcother.path() and fcother.data() == \
399 399 fcancestor.data():
400 400 return 0
401 401 if fcancestor.path() != fcdest.path() and fcdest.data() == \
402 402 fcancestor.data():
403 403 repo.wwrite(fcdest.path(), fcother.data(), fcother.flags())
404 404 return 0
405 405
406 406 if repo.ui.promptchoice(_('largefile %s has a merge conflict\n'
407 407 'keep (l)ocal or take (o)ther?') %
408 408 lfutil.splitstandin(orig),
409 409 (_('&Local'), _('&Other')), 0) == 0:
410 410 return 0
411 411 else:
412 412 repo.wwrite(fcdest.path(), fcother.data(), fcother.flags())
413 413 return 0
414 414
415 415 # Copy first changes the matchers to match standins instead of
416 416 # largefiles. Then it overrides util.copyfile in that function it
417 417 # checks if the destination largefile already exists. It also keeps a
418 418 # list of copied files so that the largefiles can be copied and the
419 419 # dirstate updated.
420 420 def overridecopy(orig, ui, repo, pats, opts, rename=False):
421 421 # doesn't remove largefile on rename
422 422 if len(pats) < 2:
423 423 # this isn't legal, let the original function deal with it
424 424 return orig(ui, repo, pats, opts, rename)
425 425
426 426 def makestandin(relpath):
427 427 path = scmutil.canonpath(repo.root, repo.getcwd(), relpath)
428 428 return os.path.join(repo.wjoin(lfutil.standin(path)))
429 429
430 430 fullpats = scmutil.expandpats(pats)
431 431 dest = fullpats[-1]
432 432
433 433 if os.path.isdir(dest):
434 434 if not os.path.isdir(makestandin(dest)):
435 435 os.makedirs(makestandin(dest))
436 436 # This could copy both lfiles and normal files in one command,
437 437 # but we don't want to do that. First replace their matcher to
438 438 # only match normal files and run it, then replace it to just
439 439 # match largefiles and run it again.
440 440 nonormalfiles = False
441 441 nolfiles = False
442 442 try:
443 443 try:
444 444 installnormalfilesmatchfn(repo[None].manifest())
445 445 result = orig(ui, repo, pats, opts, rename)
446 446 except util.Abort, e:
447 447 if str(e) != _('no files to copy'):
448 448 raise e
449 449 else:
450 450 nonormalfiles = True
451 451 result = 0
452 452 finally:
453 453 restorematchfn()
454 454
455 455 # The first rename can cause our current working directory to be removed.
456 456 # In that case there is nothing left to copy/rename so just quit.
457 457 try:
458 458 repo.getcwd()
459 459 except OSError:
460 460 return result
461 461
462 462 try:
463 463 try:
464 464 # When we call orig below it creates the standins but we don't add
465 465 # them to the dir state until later so lock during that time.
466 466 wlock = repo.wlock()
467 467
468 468 manifest = repo[None].manifest()
469 469 oldmatch = None # for the closure
470 470 def overridematch(ctx, pats=[], opts={}, globbed=False,
471 471 default='relpath'):
472 472 newpats = []
473 473 # The patterns were previously mangled to add the standin
474 474 # directory; we need to remove that now
475 475 for pat in pats:
476 476 if match_.patkind(pat) is None and lfutil.shortname in pat:
477 477 newpats.append(pat.replace(lfutil.shortname, ''))
478 478 else:
479 479 newpats.append(pat)
480 480 match = oldmatch(ctx, newpats, opts, globbed, default)
481 481 m = copy.copy(match)
482 482 lfile = lambda f: lfutil.standin(f) in manifest
483 483 m._files = [lfutil.standin(f) for f in m._files if lfile(f)]
484 484 m._fmap = set(m._files)
485 485 origmatchfn = m.matchfn
486 486 m.matchfn = lambda f: (lfutil.isstandin(f) and
487 487 (f in manifest) and
488 488 origmatchfn(lfutil.splitstandin(f)) or
489 489 None)
490 490 return m
491 491 oldmatch = installmatchfn(overridematch)
492 492 listpats = []
493 493 for pat in pats:
494 494 if match_.patkind(pat) is not None:
495 495 listpats.append(pat)
496 496 else:
497 497 listpats.append(makestandin(pat))
498 498
499 499 try:
500 500 origcopyfile = util.copyfile
501 501 copiedfiles = []
502 502 def overridecopyfile(src, dest):
503 503 if (lfutil.shortname in src and
504 504 dest.startswith(repo.wjoin(lfutil.shortname))):
505 505 destlfile = dest.replace(lfutil.shortname, '')
506 506 if not opts['force'] and os.path.exists(destlfile):
507 507 raise IOError('',
508 508 _('destination largefile already exists'))
509 509 copiedfiles.append((src, dest))
510 510 origcopyfile(src, dest)
511 511
512 512 util.copyfile = overridecopyfile
513 513 result += orig(ui, repo, listpats, opts, rename)
514 514 finally:
515 515 util.copyfile = origcopyfile
516 516
517 517 lfdirstate = lfutil.openlfdirstate(ui, repo)
518 518 for (src, dest) in copiedfiles:
519 519 if (lfutil.shortname in src and
520 520 dest.startswith(repo.wjoin(lfutil.shortname))):
521 521 srclfile = src.replace(repo.wjoin(lfutil.standin('')), '')
522 522 destlfile = dest.replace(repo.wjoin(lfutil.standin('')), '')
523 523 destlfiledir = os.path.dirname(repo.wjoin(destlfile)) or '.'
524 524 if not os.path.isdir(destlfiledir):
525 525 os.makedirs(destlfiledir)
526 526 if rename:
527 527 os.rename(repo.wjoin(srclfile), repo.wjoin(destlfile))
528 528 lfdirstate.remove(srclfile)
529 529 else:
530 530 util.copyfile(repo.wjoin(srclfile),
531 531 repo.wjoin(destlfile))
532 532
533 533 lfdirstate.add(destlfile)
534 534 lfdirstate.write()
535 535 except util.Abort, e:
536 536 if str(e) != _('no files to copy'):
537 537 raise e
538 538 else:
539 539 nolfiles = True
540 540 finally:
541 541 restorematchfn()
542 542 wlock.release()
543 543
544 544 if nolfiles and nonormalfiles:
545 545 raise util.Abort(_('no files to copy'))
546 546
547 547 return result
548 548
549 549 # When the user calls revert, we have to be careful to not revert any
550 550 # changes to other largefiles accidentally. This means we have to keep
551 551 # track of the largefiles that are being reverted so we only pull down
552 552 # the necessary largefiles.
553 553 #
554 554 # Standins are only updated (to match the hash of largefiles) before
555 555 # commits. Update the standins then run the original revert, changing
556 556 # the matcher to hit standins instead of largefiles. Based on the
557 557 # resulting standins update the largefiles. Then return the standins
558 558 # to their proper state
559 559 def overriderevert(orig, ui, repo, *pats, **opts):
560 560 # Because we put the standins in a bad state (by updating them)
561 561 # and then return them to a correct state we need to lock to
562 562 # prevent others from changing them in their incorrect state.
563 563 wlock = repo.wlock()
564 564 try:
565 565 lfdirstate = lfutil.openlfdirstate(ui, repo)
566 566 (modified, added, removed, missing, unknown, ignored, clean) = \
567 567 lfutil.lfdirstatestatus(lfdirstate, repo, repo['.'].rev())
568 568 for lfile in modified:
569 569 lfutil.updatestandin(repo, lfutil.standin(lfile))
570 570 for lfile in missing:
571 571 if (os.path.exists(repo.wjoin(lfutil.standin(lfile)))):
572 572 os.unlink(repo.wjoin(lfutil.standin(lfile)))
573 573
574 574 try:
575 575 ctx = scmutil.revsingle(repo, opts.get('rev'))
576 576 oldmatch = None # for the closure
577 577 def overridematch(ctx, pats=[], opts={}, globbed=False,
578 578 default='relpath'):
579 579 match = oldmatch(ctx, pats, opts, globbed, default)
580 580 m = copy.copy(match)
581 581 def tostandin(f):
582 582 if lfutil.standin(f) in ctx:
583 583 return lfutil.standin(f)
584 584 elif lfutil.standin(f) in repo[None]:
585 585 return None
586 586 return f
587 587 m._files = [tostandin(f) for f in m._files]
588 588 m._files = [f for f in m._files if f is not None]
589 589 m._fmap = set(m._files)
590 590 origmatchfn = m.matchfn
591 591 def matchfn(f):
592 592 if lfutil.isstandin(f):
593 593 # We need to keep track of what largefiles are being
594 594 # matched so we know which ones to update later --
595 595 # otherwise we accidentally revert changes to other
596 596 # largefiles. This is repo-specific, so duckpunch the
597 597 # repo object to keep the list of largefiles for us
598 598 # later.
599 599 if origmatchfn(lfutil.splitstandin(f)) and \
600 600 (f in repo[None] or f in ctx):
601 601 lfileslist = getattr(repo, '_lfilestoupdate', [])
602 602 lfileslist.append(lfutil.splitstandin(f))
603 603 repo._lfilestoupdate = lfileslist
604 604 return True
605 605 else:
606 606 return False
607 607 return origmatchfn(f)
608 608 m.matchfn = matchfn
609 609 return m
610 610 oldmatch = installmatchfn(overridematch)
611 611 scmutil.match
612 612 matches = overridematch(repo[None], pats, opts)
613 613 orig(ui, repo, *pats, **opts)
614 614 finally:
615 615 restorematchfn()
616 616 lfileslist = getattr(repo, '_lfilestoupdate', [])
617 617 lfcommands.updatelfiles(ui, repo, filelist=lfileslist,
618 618 printmessage=False)
619 619
620 620 # empty out the largefiles list so we start fresh next time
621 621 repo._lfilestoupdate = []
622 622 for lfile in modified:
623 623 if lfile in lfileslist:
624 624 if os.path.exists(repo.wjoin(lfutil.standin(lfile))) and lfile\
625 625 in repo['.']:
626 626 lfutil.writestandin(repo, lfutil.standin(lfile),
627 627 repo['.'][lfile].data().strip(),
628 628 'x' in repo['.'][lfile].flags())
629 629 lfdirstate = lfutil.openlfdirstate(ui, repo)
630 630 for lfile in added:
631 631 standin = lfutil.standin(lfile)
632 632 if standin not in ctx and (standin in matches or opts.get('all')):
633 633 if lfile in lfdirstate:
634 634 lfdirstate.drop(lfile)
635 635 util.unlinkpath(repo.wjoin(standin))
636 636 lfdirstate.write()
637 637 finally:
638 638 wlock.release()
639 639
640 640 def hgupdate(orig, repo, node):
641 641 # Only call updatelfiles the standins that have changed to save time
642 642 oldstandins = lfutil.getstandinsstate(repo)
643 643 result = orig(repo, node)
644 644 newstandins = lfutil.getstandinsstate(repo)
645 645 filelist = lfutil.getlfilestoupdate(oldstandins, newstandins)
646 646 lfcommands.updatelfiles(repo.ui, repo, filelist=filelist, printmessage=True)
647 647 return result
648 648
649 649 def hgclean(orig, repo, node, show_stats=True):
650 650 result = orig(repo, node, show_stats)
651 651 lfcommands.updatelfiles(repo.ui, repo)
652 652 return result
653 653
654 654 def hgmerge(orig, repo, node, force=None, remind=True):
655 655 # Mark the repo as being in the middle of a merge, so that
656 656 # updatelfiles() will know that it needs to trust the standins in
657 657 # the working copy, not in the standins in the current node
658 658 repo._ismerging = True
659 659 try:
660 660 result = orig(repo, node, force, remind)
661 661 lfcommands.updatelfiles(repo.ui, repo)
662 662 finally:
663 663 repo._ismerging = False
664 664 return result
665 665
666 666 # When we rebase a repository with remotely changed largefiles, we need to
667 667 # take some extra care so that the largefiles are correctly updated in the
668 668 # working copy
669 669 def overridepull(orig, ui, repo, source=None, **opts):
670 670 revsprepull = len(repo)
671 671 if opts.get('rebase', False):
672 672 repo._isrebasing = True
673 673 try:
674 674 if opts.get('update'):
675 675 del opts['update']
676 676 ui.debug('--update and --rebase are not compatible, ignoring '
677 677 'the update flag\n')
678 678 del opts['rebase']
679 679 cmdutil.bailifchanged(repo)
680 680 origpostincoming = commands.postincoming
681 681 def _dummy(*args, **kwargs):
682 682 pass
683 683 commands.postincoming = _dummy
684 684 if not source:
685 685 source = 'default'
686 686 repo.lfpullsource = source
687 687 try:
688 688 result = commands.pull(ui, repo, source, **opts)
689 689 finally:
690 690 commands.postincoming = origpostincoming
691 691 revspostpull = len(repo)
692 692 if revspostpull > revsprepull:
693 693 result = result or rebase.rebase(ui, repo)
694 694 finally:
695 695 repo._isrebasing = False
696 696 else:
697 697 if not source:
698 698 source = 'default'
699 699 repo.lfpullsource = source
700 700 oldheads = lfutil.getcurrentheads(repo)
701 701 result = orig(ui, repo, source, **opts)
702 702 # If we do not have the new largefiles for any new heads we pulled, we
703 703 # will run into a problem later if we try to merge or rebase with one of
704 704 # these heads, so cache the largefiles now directly into the system
705 705 # cache.
706 706 ui.status(_("caching new largefiles\n"))
707 707 numcached = 0
708 708 heads = lfutil.getcurrentheads(repo)
709 709 newheads = set(heads).difference(set(oldheads))
710 710 for head in newheads:
711 711 (cached, missing) = lfcommands.cachelfiles(ui, repo, head)
712 712 numcached += len(cached)
713 713 ui.status(_("%d largefiles cached\n") % numcached)
714 714 if opts.get('all_largefiles'):
715 715 revspostpull = len(repo)
716 716 revs = []
717 717 for rev in xrange(revsprepull + 1, revspostpull):
718 718 revs.append(repo[rev].rev())
719 719 lfcommands.downloadlfiles(ui, repo, revs)
720 720 return result
721 721
722 722 def overrideclone(orig, ui, source, dest=None, **opts):
723 723 d = dest
724 724 if d is None:
725 725 d = hg.defaultdest(source)
726 726 if opts.get('all_largefiles') and not hg.islocal(d):
727 727 raise util.Abort(_(
728 728 '--all-largefiles is incompatible with non-local destination %s' %
729 729 d))
730 730
731 731 return orig(ui, source, dest, **opts)
732 732
733 733 def hgclone(orig, ui, opts, *args, **kwargs):
734 734 result = orig(ui, opts, *args, **kwargs)
735 735
736 736 if result is not None:
737 737 sourcerepo, destrepo = result
738 738 repo = destrepo.local()
739 739
740 740 # The .hglf directory must exist for the standin matcher to match
741 741 # anything (which listlfiles uses for each rev), and .hg/largefiles is
742 742 # assumed to exist by the code that caches the downloaded file. These
743 743 # directories exist if clone updated to any rev. (If the repo does not
744 744 # have largefiles, download never gets to the point of needing
745 745 # .hg/largefiles, and the standin matcher won't match anything anyway.)
746 746 if 'largefiles' in repo.requirements:
747 747 if opts.get('noupdate'):
748 748 util.makedirs(repo.pathto(lfutil.shortname))
749 749 util.makedirs(repo.join(lfutil.longname))
750 750
751 751 # Caching is implicitly limited to 'rev' option, since the dest repo was
752 752 # truncated at that point. The user may expect a download count with
753 753 # this option, so attempt whether or not this is a largefile repo.
754 754 if opts.get('all_largefiles'):
755 755 success, missing = lfcommands.downloadlfiles(ui, repo, None)
756 756
757 757 if missing != 0:
758 758 return None
759 759
760 760 return result
761 761
762 762 def overriderebase(orig, ui, repo, **opts):
763 763 repo._isrebasing = True
764 764 try:
765 765 return orig(ui, repo, **opts)
766 766 finally:
767 767 repo._isrebasing = False
768 768
769 769 def overridearchive(orig, repo, dest, node, kind, decode=True, matchfn=None,
770 770 prefix=None, mtime=None, subrepos=None):
771 771 # No need to lock because we are only reading history and
772 772 # largefile caches, neither of which are modified.
773 773 lfcommands.cachelfiles(repo.ui, repo, node)
774 774
775 775 if kind not in archival.archivers:
776 776 raise util.Abort(_("unknown archive type '%s'") % kind)
777 777
778 778 ctx = repo[node]
779 779
780 780 if kind == 'files':
781 781 if prefix:
782 782 raise util.Abort(
783 783 _('cannot give prefix when archiving to files'))
784 784 else:
785 785 prefix = archival.tidyprefix(dest, kind, prefix)
786 786
787 787 def write(name, mode, islink, getdata):
788 788 if matchfn and not matchfn(name):
789 789 return
790 790 data = getdata()
791 791 if decode:
792 792 data = repo.wwritedata(name, data)
793 793 archiver.addfile(prefix + name, mode, islink, data)
794 794
795 795 archiver = archival.archivers[kind](dest, mtime or ctx.date()[0])
796 796
797 797 if repo.ui.configbool("ui", "archivemeta", True):
798 798 def metadata():
799 799 base = 'repo: %s\nnode: %s\nbranch: %s\n' % (
800 800 hex(repo.changelog.node(0)), hex(node), ctx.branch())
801 801
802 802 tags = ''.join('tag: %s\n' % t for t in ctx.tags()
803 803 if repo.tagtype(t) == 'global')
804 804 if not tags:
805 805 repo.ui.pushbuffer()
806 806 opts = {'template': '{latesttag}\n{latesttagdistance}',
807 807 'style': '', 'patch': None, 'git': None}
808 808 cmdutil.show_changeset(repo.ui, repo, opts).show(ctx)
809 809 ltags, dist = repo.ui.popbuffer().split('\n')
810 810 tags = ''.join('latesttag: %s\n' % t for t in ltags.split(':'))
811 811 tags += 'latesttagdistance: %s\n' % dist
812 812
813 813 return base + tags
814 814
815 815 write('.hg_archival.txt', 0644, False, metadata)
816 816
817 817 for f in ctx:
818 818 ff = ctx.flags(f)
819 819 getdata = ctx[f].data
820 820 if lfutil.isstandin(f):
821 821 path = lfutil.findfile(repo, getdata().strip())
822 822 if path is None:
823 823 raise util.Abort(
824 824 _('largefile %s not found in repo store or system cache')
825 825 % lfutil.splitstandin(f))
826 826 f = lfutil.splitstandin(f)
827 827
828 828 def getdatafn():
829 829 fd = None
830 830 try:
831 831 fd = open(path, 'rb')
832 832 return fd.read()
833 833 finally:
834 834 if fd:
835 835 fd.close()
836 836
837 837 getdata = getdatafn
838 838 write(f, 'x' in ff and 0755 or 0644, 'l' in ff, getdata)
839 839
840 840 if subrepos:
841 841 for subpath in ctx.substate:
842 842 sub = ctx.sub(subpath)
843 843 submatch = match_.narrowmatcher(subpath, matchfn)
844 844 sub.archive(repo.ui, archiver, prefix, submatch)
845 845
846 846 archiver.done()
847 847
848 848 def hgsubrepoarchive(orig, repo, ui, archiver, prefix, match=None):
849 849 repo._get(repo._state + ('hg',))
850 850 rev = repo._state[1]
851 851 ctx = repo._repo[rev]
852 852
853 853 lfcommands.cachelfiles(ui, repo._repo, ctx.node())
854 854
855 855 def write(name, mode, islink, getdata):
856 856 # At this point, the standin has been replaced with the largefile name,
857 857 # so the normal matcher works here without the lfutil variants.
858 858 if match and not match(f):
859 859 return
860 860 data = getdata()
861 861
862 862 archiver.addfile(prefix + repo._path + '/' + name, mode, islink, data)
863 863
864 864 for f in ctx:
865 865 ff = ctx.flags(f)
866 866 getdata = ctx[f].data
867 867 if lfutil.isstandin(f):
868 868 path = lfutil.findfile(repo._repo, getdata().strip())
869 869 if path is None:
870 870 raise util.Abort(
871 871 _('largefile %s not found in repo store or system cache')
872 872 % lfutil.splitstandin(f))
873 873 f = lfutil.splitstandin(f)
874 874
875 875 def getdatafn():
876 876 fd = None
877 877 try:
878 878 fd = open(os.path.join(prefix, path), 'rb')
879 879 return fd.read()
880 880 finally:
881 881 if fd:
882 882 fd.close()
883 883
884 884 getdata = getdatafn
885 885
886 886 write(f, 'x' in ff and 0755 or 0644, 'l' in ff, getdata)
887 887
888 888 for subpath in ctx.substate:
889 889 sub = ctx.sub(subpath)
890 890 submatch = match_.narrowmatcher(subpath, match)
891 891 sub.archive(ui, archiver, os.path.join(prefix, repo._path) + '/',
892 892 submatch)
893 893
894 894 # If a largefile is modified, the change is not reflected in its
895 895 # standin until a commit. cmdutil.bailifchanged() raises an exception
896 896 # if the repo has uncommitted changes. Wrap it to also check if
897 897 # largefiles were changed. This is used by bisect and backout.
898 898 def overridebailifchanged(orig, repo):
899 899 orig(repo)
900 900 repo.lfstatus = True
901 901 modified, added, removed, deleted = repo.status()[:4]
902 902 repo.lfstatus = False
903 903 if modified or added or removed or deleted:
904 904 raise util.Abort(_('outstanding uncommitted changes'))
905 905
906 906 # Fetch doesn't use cmdutil.bailifchanged so override it to add the check
907 907 def overridefetch(orig, ui, repo, *pats, **opts):
908 908 repo.lfstatus = True
909 909 modified, added, removed, deleted = repo.status()[:4]
910 910 repo.lfstatus = False
911 911 if modified or added or removed or deleted:
912 912 raise util.Abort(_('outstanding uncommitted changes'))
913 913 return orig(ui, repo, *pats, **opts)
914 914
915 915 def overrideforget(orig, ui, repo, *pats, **opts):
916 916 installnormalfilesmatchfn(repo[None].manifest())
917 917 result = orig(ui, repo, *pats, **opts)
918 918 restorematchfn()
919 919 m = scmutil.match(repo[None], pats, opts)
920 920
921 921 try:
922 922 repo.lfstatus = True
923 923 s = repo.status(match=m, clean=True)
924 924 finally:
925 925 repo.lfstatus = False
926 926 forget = sorted(s[0] + s[1] + s[3] + s[6])
927 927 forget = [f for f in forget if lfutil.standin(f) in repo[None].manifest()]
928 928
929 929 for f in forget:
930 930 if lfutil.standin(f) not in repo.dirstate and not \
931 931 os.path.isdir(m.rel(lfutil.standin(f))):
932 932 ui.warn(_('not removing %s: file is already untracked\n')
933 933 % m.rel(f))
934 934 result = 1
935 935
936 936 for f in forget:
937 937 if ui.verbose or not m.exact(f):
938 938 ui.status(_('removing %s\n') % m.rel(f))
939 939
940 940 # Need to lock because standin files are deleted then removed from the
941 941 # repository and we could race in-between.
942 942 wlock = repo.wlock()
943 943 try:
944 944 lfdirstate = lfutil.openlfdirstate(ui, repo)
945 945 for f in forget:
946 946 if lfdirstate[f] == 'a':
947 947 lfdirstate.drop(f)
948 948 else:
949 949 lfdirstate.remove(f)
950 950 lfdirstate.write()
951 951 lfutil.reporemove(repo, [lfutil.standin(f) for f in forget],
952 952 unlink=True)
953 953 finally:
954 954 wlock.release()
955 955
956 956 return result
957 957
958 958 def getoutgoinglfiles(ui, repo, dest=None, **opts):
959 959 dest = ui.expandpath(dest or 'default-push', dest or 'default')
960 960 dest, branches = hg.parseurl(dest, opts.get('branch'))
961 961 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
962 962 if revs:
963 963 revs = [repo.lookup(rev) for rev in scmutil.revrange(repo, revs)]
964 964
965 965 try:
966 966 remote = hg.peer(repo, opts, dest)
967 967 except error.RepoError:
968 968 return None
969 969 o = lfutil.findoutgoing(repo, remote, False)
970 970 if not o:
971 971 return o
972 972 o = repo.changelog.nodesbetween(o, revs)[0]
973 973 if opts.get('newest_first'):
974 974 o.reverse()
975 975
976 976 toupload = set()
977 977 for n in o:
978 978 parents = [p for p in repo.changelog.parents(n) if p != node.nullid]
979 979 ctx = repo[n]
980 980 files = set(ctx.files())
981 981 if len(parents) == 2:
982 982 mc = ctx.manifest()
983 983 mp1 = ctx.parents()[0].manifest()
984 984 mp2 = ctx.parents()[1].manifest()
985 985 for f in mp1:
986 986 if f not in mc:
987 987 files.add(f)
988 988 for f in mp2:
989 989 if f not in mc:
990 990 files.add(f)
991 991 for f in mc:
992 992 if mc[f] != mp1.get(f, None) or mc[f] != mp2.get(f, None):
993 993 files.add(f)
994 994 toupload = toupload.union(
995 995 set([f for f in files if lfutil.isstandin(f) and f in ctx]))
996 996 return toupload
997 997
998 998 def overrideoutgoing(orig, ui, repo, dest=None, **opts):
999 999 result = orig(ui, repo, dest, **opts)
1000 1000
1001 1001 if opts.pop('large', None):
1002 1002 toupload = getoutgoinglfiles(ui, repo, dest, **opts)
1003 1003 if toupload is None:
1004 1004 ui.status(_('largefiles: No remote repo\n'))
1005 1005 elif not toupload:
1006 1006 ui.status(_('largefiles: no files to upload\n'))
1007 1007 else:
1008 1008 ui.status(_('largefiles to upload:\n'))
1009 1009 for file in toupload:
1010 1010 ui.status(lfutil.splitstandin(file) + '\n')
1011 1011 ui.status('\n')
1012 1012
1013 1013 return result
1014 1014
1015 1015 def overridesummary(orig, ui, repo, *pats, **opts):
1016 1016 try:
1017 1017 repo.lfstatus = True
1018 1018 orig(ui, repo, *pats, **opts)
1019 1019 finally:
1020 1020 repo.lfstatus = False
1021 1021
1022 1022 if opts.pop('large', None):
1023 1023 toupload = getoutgoinglfiles(ui, repo, None, **opts)
1024 1024 if toupload is None:
1025 1025 # i18n: column positioning for "hg summary"
1026 1026 ui.status(_('largefiles: (no remote repo)\n'))
1027 1027 elif not toupload:
1028 1028 # i18n: column positioning for "hg summary"
1029 1029 ui.status(_('largefiles: (no files to upload)\n'))
1030 1030 else:
1031 1031 # i18n: column positioning for "hg summary"
1032 1032 ui.status(_('largefiles: %d to upload\n') % len(toupload))
1033 1033
1034 1034 def scmutiladdremove(orig, repo, pats=[], opts={}, dry_run=None,
1035 1035 similarity=None):
1036 1036 if not lfutil.islfilesrepo(repo):
1037 1037 return orig(repo, pats, opts, dry_run, similarity)
1038 1038 # Get the list of missing largefiles so we can remove them
1039 1039 lfdirstate = lfutil.openlfdirstate(repo.ui, repo)
1040 1040 s = lfdirstate.status(match_.always(repo.root, repo.getcwd()), [], False,
1041 1041 False, False)
1042 1042 (unsure, modified, added, removed, missing, unknown, ignored, clean) = s
1043 1043
1044 1044 # Call into the normal remove code, but the removing of the standin, we want
1045 1045 # to have handled by original addremove. Monkey patching here makes sure
1046 1046 # we don't remove the standin in the largefiles code, preventing a very
1047 1047 # confused state later.
1048 1048 if missing:
1049 1049 m = [repo.wjoin(f) for f in missing]
1050 1050 repo._isaddremove = True
1051 1051 removelargefiles(repo.ui, repo, *m, **opts)
1052 1052 repo._isaddremove = False
1053 1053 # Call into the normal add code, and any files that *should* be added as
1054 1054 # largefiles will be
1055 1055 addlargefiles(repo.ui, repo, *pats, **opts)
1056 1056 # Now that we've handled largefiles, hand off to the original addremove
1057 1057 # function to take care of the rest. Make sure it doesn't do anything with
1058 1058 # largefiles by installing a matcher that will ignore them.
1059 1059 installnormalfilesmatchfn(repo[None].manifest())
1060 1060 result = orig(repo, pats, opts, dry_run, similarity)
1061 1061 restorematchfn()
1062 1062 return result
1063 1063
1064 1064 # Calling purge with --all will cause the largefiles to be deleted.
1065 1065 # Override repo.status to prevent this from happening.
1066 1066 def overridepurge(orig, ui, repo, *dirs, **opts):
1067 # XXX large file status is buggy when used on repo proxy.
1068 # XXX this needs to be investigate.
1069 repo = repo.unfiltered()
1067 1070 oldstatus = repo.status
1068 1071 def overridestatus(node1='.', node2=None, match=None, ignored=False,
1069 1072 clean=False, unknown=False, listsubrepos=False):
1070 1073 r = oldstatus(node1, node2, match, ignored, clean, unknown,
1071 1074 listsubrepos)
1072 1075 lfdirstate = lfutil.openlfdirstate(ui, repo)
1073 1076 modified, added, removed, deleted, unknown, ignored, clean = r
1074 1077 unknown = [f for f in unknown if lfdirstate[f] == '?']
1075 1078 ignored = [f for f in ignored if lfdirstate[f] == '?']
1076 1079 return modified, added, removed, deleted, unknown, ignored, clean
1077 1080 repo.status = overridestatus
1078 1081 orig(ui, repo, *dirs, **opts)
1079 1082 repo.status = oldstatus
1080 1083
1081 1084 def overriderollback(orig, ui, repo, **opts):
1082 1085 result = orig(ui, repo, **opts)
1083 1086 merge.update(repo, node=None, branchmerge=False, force=True,
1084 1087 partial=lfutil.isstandin)
1085 1088 wlock = repo.wlock()
1086 1089 try:
1087 1090 lfdirstate = lfutil.openlfdirstate(ui, repo)
1088 1091 lfiles = lfutil.listlfiles(repo)
1089 1092 oldlfiles = lfutil.listlfiles(repo, repo[None].parents()[0].rev())
1090 1093 for file in lfiles:
1091 1094 if file in oldlfiles:
1092 1095 lfdirstate.normallookup(file)
1093 1096 else:
1094 1097 lfdirstate.add(file)
1095 1098 lfdirstate.write()
1096 1099 finally:
1097 1100 wlock.release()
1098 1101 return result
1099 1102
1100 1103 def overridetransplant(orig, ui, repo, *revs, **opts):
1101 1104 try:
1102 1105 oldstandins = lfutil.getstandinsstate(repo)
1103 1106 repo._istransplanting = True
1104 1107 result = orig(ui, repo, *revs, **opts)
1105 1108 newstandins = lfutil.getstandinsstate(repo)
1106 1109 filelist = lfutil.getlfilestoupdate(oldstandins, newstandins)
1107 1110 lfcommands.updatelfiles(repo.ui, repo, filelist=filelist,
1108 1111 printmessage=True)
1109 1112 finally:
1110 1113 repo._istransplanting = False
1111 1114 return result
1112 1115
1113 1116 def overridecat(orig, ui, repo, file1, *pats, **opts):
1114 1117 ctx = scmutil.revsingle(repo, opts.get('rev'))
1115 1118 if not lfutil.standin(file1) in ctx:
1116 1119 result = orig(ui, repo, file1, *pats, **opts)
1117 1120 return result
1118 1121 return lfcommands.catlfile(repo, file1, ctx.rev(), opts.get('output'))
1119 1122
1120 1123 def mercurialsinkbefore(orig, sink):
1121 1124 sink.repo._isconverting = True
1122 1125 orig(sink)
1123 1126
1124 1127 def mercurialsinkafter(orig, sink):
1125 1128 sink.repo._isconverting = False
1126 1129 orig(sink)
@@ -1,475 +1,479 b''
1 1 # Copyright 2009-2010 Gregory P. Ward
2 2 # Copyright 2009-2010 Intelerad Medical Systems Incorporated
3 3 # Copyright 2010-2011 Fog Creek Software
4 4 # Copyright 2010-2011 Unity Technologies
5 5 #
6 6 # This software may be used and distributed according to the terms of the
7 7 # GNU General Public License version 2 or any later version.
8 8
9 9 '''setup for largefiles repositories: reposetup'''
10 10 import copy
11 11 import types
12 12 import os
13 13
14 14 from mercurial import context, error, manifest, match as match_, util
15 15 from mercurial import node as node_
16 16 from mercurial.i18n import _
17 from mercurial import localrepo
17 18
18 19 import lfcommands
19 20 import proto
20 21 import lfutil
21 22
22 23 def reposetup(ui, repo):
23 24 # wire repositories should be given new wireproto functions but not the
24 25 # other largefiles modifications
25 26 if not repo.local():
26 27 return proto.wirereposetup(ui, repo)
27 28
28 29 for name in ('status', 'commitctx', 'commit', 'push'):
29 30 method = getattr(repo, name)
30 31 if (isinstance(method, types.FunctionType) and
31 32 method.func_name == 'wrap'):
32 33 ui.warn(_('largefiles: repo method %r appears to have already been'
33 34 ' wrapped by another extension: '
34 35 'largefiles may behave incorrectly\n')
35 36 % name)
36 37
37 38 class lfilesrepo(repo.__class__):
38 39 lfstatus = False
39 40 def status_nolfiles(self, *args, **kwargs):
40 41 return super(lfilesrepo, self).status(*args, **kwargs)
41 42
42 43 # When lfstatus is set, return a context that gives the names
43 44 # of largefiles instead of their corresponding standins and
44 45 # identifies the largefiles as always binary, regardless of
45 46 # their actual contents.
46 47 def __getitem__(self, changeid):
47 48 ctx = super(lfilesrepo, self).__getitem__(changeid)
48 49 if self.lfstatus:
49 50 class lfilesmanifestdict(manifest.manifestdict):
50 51 def __contains__(self, filename):
51 52 if super(lfilesmanifestdict,
52 53 self).__contains__(filename):
53 54 return True
54 55 return super(lfilesmanifestdict,
55 56 self).__contains__(lfutil.standin(filename))
56 57 class lfilesctx(ctx.__class__):
57 58 def files(self):
58 59 filenames = super(lfilesctx, self).files()
59 60 return [lfutil.splitstandin(f) or f for f in filenames]
60 61 def manifest(self):
61 62 man1 = super(lfilesctx, self).manifest()
62 63 man1.__class__ = lfilesmanifestdict
63 64 return man1
64 65 def filectx(self, path, fileid=None, filelog=None):
65 66 try:
66 67 if filelog is not None:
67 68 result = super(lfilesctx, self).filectx(
68 69 path, fileid, filelog)
69 70 else:
70 71 result = super(lfilesctx, self).filectx(
71 72 path, fileid)
72 73 except error.LookupError:
73 74 # Adding a null character will cause Mercurial to
74 75 # identify this as a binary file.
75 76 if filelog is not None:
76 77 result = super(lfilesctx, self).filectx(
77 78 lfutil.standin(path), fileid, filelog)
78 79 else:
79 80 result = super(lfilesctx, self).filectx(
80 81 lfutil.standin(path), fileid)
81 82 olddata = result.data
82 83 result.data = lambda: olddata() + '\0'
83 84 return result
84 85 ctx.__class__ = lfilesctx
85 86 return ctx
86 87
87 88 # Figure out the status of big files and insert them into the
88 89 # appropriate list in the result. Also removes standin files
89 90 # from the listing. Revert to the original status if
90 91 # self.lfstatus is False.
92 # XXX large file status is buggy when used on repo proxy.
93 # XXX this needs to be investigated.
94 @localrepo.unfilteredmeth
91 95 def status(self, node1='.', node2=None, match=None, ignored=False,
92 96 clean=False, unknown=False, listsubrepos=False):
93 97 listignored, listclean, listunknown = ignored, clean, unknown
94 98 if not self.lfstatus:
95 99 return super(lfilesrepo, self).status(node1, node2, match,
96 100 listignored, listclean, listunknown, listsubrepos)
97 101 else:
98 102 # some calls in this function rely on the old version of status
99 103 self.lfstatus = False
100 104 if isinstance(node1, context.changectx):
101 105 ctx1 = node1
102 106 else:
103 107 ctx1 = self[node1]
104 108 if isinstance(node2, context.changectx):
105 109 ctx2 = node2
106 110 else:
107 111 ctx2 = self[node2]
108 112 working = ctx2.rev() is None
109 113 parentworking = working and ctx1 == self['.']
110 114
111 115 def inctx(file, ctx):
112 116 try:
113 117 if ctx.rev() is None:
114 118 return file in ctx.manifest()
115 119 ctx[file]
116 120 return True
117 121 except KeyError:
118 122 return False
119 123
120 124 if match is None:
121 125 match = match_.always(self.root, self.getcwd())
122 126
123 127 # First check if there were files specified on the
124 128 # command line. If there were, and none of them were
125 129 # largefiles, we should just bail here and let super
126 130 # handle it -- thus gaining a big performance boost.
127 131 lfdirstate = lfutil.openlfdirstate(ui, self)
128 132 if match.files() and not match.anypats():
129 133 for f in lfdirstate:
130 134 if match(f):
131 135 break
132 136 else:
133 137 return super(lfilesrepo, self).status(node1, node2,
134 138 match, listignored, listclean,
135 139 listunknown, listsubrepos)
136 140
137 141 # Create a copy of match that matches standins instead
138 142 # of largefiles.
139 143 def tostandins(files):
140 144 if not working:
141 145 return files
142 146 newfiles = []
143 147 dirstate = self.dirstate
144 148 for f in files:
145 149 sf = lfutil.standin(f)
146 150 if sf in dirstate:
147 151 newfiles.append(sf)
148 152 elif sf in dirstate.dirs():
149 153 # Directory entries could be regular or
150 154 # standin, check both
151 155 newfiles.extend((f, sf))
152 156 else:
153 157 newfiles.append(f)
154 158 return newfiles
155 159
156 160 # Create a function that we can use to override what is
157 161 # normally the ignore matcher. We've already checked
158 162 # for ignored files on the first dirstate walk, and
159 163 # unnecessarily re-checking here causes a huge performance
160 164 # hit because lfdirstate only knows about largefiles
161 165 def _ignoreoverride(self):
162 166 return False
163 167
164 168 m = copy.copy(match)
165 169 m._files = tostandins(m._files)
166 170
167 171 # Get ignored files here even if we weren't asked for them; we
168 172 # must use the result here for filtering later
169 173 result = super(lfilesrepo, self).status(node1, node2, m,
170 174 True, clean, unknown, listsubrepos)
171 175 if working:
172 176 try:
173 177 # Any non-largefiles that were explicitly listed must be
174 178 # taken out or lfdirstate.status will report an error.
175 179 # The status of these files was already computed using
176 180 # super's status.
177 181 # Override lfdirstate's ignore matcher to not do
178 182 # anything
179 183 origignore = lfdirstate._ignore
180 184 lfdirstate._ignore = _ignoreoverride
181 185
182 186 def sfindirstate(f):
183 187 sf = lfutil.standin(f)
184 188 dirstate = self.dirstate
185 189 return sf in dirstate or sf in dirstate.dirs()
186 190 match._files = [f for f in match._files
187 191 if sfindirstate(f)]
188 192 # Don't waste time getting the ignored and unknown
189 193 # files again; we already have them
190 194 s = lfdirstate.status(match, [], False,
191 195 listclean, False)
192 196 (unsure, modified, added, removed, missing, unknown,
193 197 ignored, clean) = s
194 198 # Replace the list of ignored and unknown files with
195 199 # the previously calculated lists, and strip out the
196 200 # largefiles
197 201 lfiles = set(lfdirstate._map)
198 202 ignored = set(result[5]).difference(lfiles)
199 203 unknown = set(result[4]).difference(lfiles)
200 204 if parentworking:
201 205 for lfile in unsure:
202 206 standin = lfutil.standin(lfile)
203 207 if standin not in ctx1:
204 208 # from second parent
205 209 modified.append(lfile)
206 210 elif ctx1[standin].data().strip() \
207 211 != lfutil.hashfile(self.wjoin(lfile)):
208 212 modified.append(lfile)
209 213 else:
210 214 clean.append(lfile)
211 215 lfdirstate.normal(lfile)
212 216 else:
213 217 tocheck = unsure + modified + added + clean
214 218 modified, added, clean = [], [], []
215 219
216 220 for lfile in tocheck:
217 221 standin = lfutil.standin(lfile)
218 222 if inctx(standin, ctx1):
219 223 if ctx1[standin].data().strip() != \
220 224 lfutil.hashfile(self.wjoin(lfile)):
221 225 modified.append(lfile)
222 226 else:
223 227 clean.append(lfile)
224 228 else:
225 229 added.append(lfile)
226 230 finally:
227 231 # Replace the original ignore function
228 232 lfdirstate._ignore = origignore
229 233
230 234 for standin in ctx1.manifest():
231 235 if not lfutil.isstandin(standin):
232 236 continue
233 237 lfile = lfutil.splitstandin(standin)
234 238 if not match(lfile):
235 239 continue
236 240 if lfile not in lfdirstate:
237 241 removed.append(lfile)
238 242
239 243 # Filter result lists
240 244 result = list(result)
241 245
242 246 # Largefiles are not really removed when they're
243 247 # still in the normal dirstate. Likewise, normal
244 248 # files are not really removed if it's still in
245 249 # lfdirstate. This happens in merges where files
246 250 # change type.
247 251 removed = [f for f in removed if f not in self.dirstate]
248 252 result[2] = [f for f in result[2] if f not in lfdirstate]
249 253
250 254 # Unknown files
251 255 unknown = set(unknown).difference(ignored)
252 256 result[4] = [f for f in unknown
253 257 if (self.dirstate[f] == '?' and
254 258 not lfutil.isstandin(f))]
255 259 # Ignored files were calculated earlier by the dirstate,
256 260 # and we already stripped out the largefiles from the list
257 261 result[5] = ignored
258 262 # combine normal files and largefiles
259 263 normals = [[fn for fn in filelist
260 264 if not lfutil.isstandin(fn)]
261 265 for filelist in result]
262 266 lfiles = (modified, added, removed, missing, [], [], clean)
263 267 result = [sorted(list1 + list2)
264 268 for (list1, list2) in zip(normals, lfiles)]
265 269 else:
266 270 def toname(f):
267 271 if lfutil.isstandin(f):
268 272 return lfutil.splitstandin(f)
269 273 return f
270 274 result = [[toname(f) for f in items] for items in result]
271 275
272 276 if not listunknown:
273 277 result[4] = []
274 278 if not listignored:
275 279 result[5] = []
276 280 if not listclean:
277 281 result[6] = []
278 282 self.lfstatus = True
279 283 return result
280 284
281 285 # As part of committing, copy all of the largefiles into the
282 286 # cache.
283 287 def commitctx(self, *args, **kwargs):
284 288 node = super(lfilesrepo, self).commitctx(*args, **kwargs)
285 289 lfutil.copyalltostore(self, node)
286 290 return node
287 291
288 292 # Before commit, largefile standins have not had their
289 293 # contents updated to reflect the hash of their largefile.
290 294 # Do that here.
291 295 def commit(self, text="", user=None, date=None, match=None,
292 296 force=False, editor=False, extra={}):
293 297 orig = super(lfilesrepo, self).commit
294 298
295 299 wlock = self.wlock()
296 300 try:
297 301 # Case 0: Rebase or Transplant
298 302 # We have to take the time to pull down the new largefiles now.
299 303 # Otherwise, any largefiles that were modified in the
300 304 # destination changesets get overwritten, either by the rebase
301 305 # or in the first commit after the rebase or transplant.
302 306 # updatelfiles will update the dirstate to mark any pulled
303 307 # largefiles as modified
304 308 if getattr(self, "_isrebasing", False) or \
305 309 getattr(self, "_istransplanting", False):
306 310 lfcommands.updatelfiles(self.ui, self, filelist=None,
307 311 printmessage=False)
308 312 result = orig(text=text, user=user, date=date, match=match,
309 313 force=force, editor=editor, extra=extra)
310 314 return result
311 315 # Case 1: user calls commit with no specific files or
312 316 # include/exclude patterns: refresh and commit all files that
313 317 # are "dirty".
314 318 if ((match is None) or
315 319 (not match.anypats() and not match.files())):
316 320 # Spend a bit of time here to get a list of files we know
317 321 # are modified so we can compare only against those.
318 322 # It can cost a lot of time (several seconds)
319 323 # otherwise to update all standins if the largefiles are
320 324 # large.
321 325 lfdirstate = lfutil.openlfdirstate(ui, self)
322 326 dirtymatch = match_.always(self.root, self.getcwd())
323 327 s = lfdirstate.status(dirtymatch, [], False, False, False)
324 328 modifiedfiles = []
325 329 for i in s:
326 330 modifiedfiles.extend(i)
327 331 lfiles = lfutil.listlfiles(self)
328 332 # this only loops through largefiles that exist (not
329 333 # removed/renamed)
330 334 for lfile in lfiles:
331 335 if lfile in modifiedfiles:
332 336 if os.path.exists(
333 337 self.wjoin(lfutil.standin(lfile))):
334 338 # this handles the case where a rebase is being
335 339 # performed and the working copy is not updated
336 340 # yet.
337 341 if os.path.exists(self.wjoin(lfile)):
338 342 lfutil.updatestandin(self,
339 343 lfutil.standin(lfile))
340 344 lfdirstate.normal(lfile)
341 345
342 346 result = orig(text=text, user=user, date=date, match=match,
343 347 force=force, editor=editor, extra=extra)
344 348
345 349 if result is not None:
346 350 for lfile in lfdirstate:
347 351 if lfile in modifiedfiles:
348 352 if (not os.path.exists(self.wjoin(
349 353 lfutil.standin(lfile)))) or \
350 354 (not os.path.exists(self.wjoin(lfile))):
351 355 lfdirstate.drop(lfile)
352 356
353 357 # This needs to be after commit; otherwise precommit hooks
354 358 # get the wrong status
355 359 lfdirstate.write()
356 360 return result
357 361
358 362 for f in match.files():
359 363 if lfutil.isstandin(f):
360 364 raise util.Abort(
361 365 _('file "%s" is a largefile standin') % f,
362 366 hint=('commit the largefile itself instead'))
363 367
364 368 # Case 2: user calls commit with specified patterns: refresh
365 369 # any matching big files.
366 370 smatcher = lfutil.composestandinmatcher(self, match)
367 371 standins = lfutil.dirstatewalk(self.dirstate, smatcher)
368 372
369 373 # No matching big files: get out of the way and pass control to
370 374 # the usual commit() method.
371 375 if not standins:
372 376 return orig(text=text, user=user, date=date, match=match,
373 377 force=force, editor=editor, extra=extra)
374 378
375 379 # Refresh all matching big files. It's possible that the
376 380 # commit will end up failing, in which case the big files will
377 381 # stay refreshed. No harm done: the user modified them and
378 382 # asked to commit them, so sooner or later we're going to
379 383 # refresh the standins. Might as well leave them refreshed.
380 384 lfdirstate = lfutil.openlfdirstate(ui, self)
381 385 for standin in standins:
382 386 lfile = lfutil.splitstandin(standin)
383 387 if lfdirstate[lfile] <> 'r':
384 388 lfutil.updatestandin(self, standin)
385 389 lfdirstate.normal(lfile)
386 390 else:
387 391 lfdirstate.drop(lfile)
388 392
389 393 # Cook up a new matcher that only matches regular files or
390 394 # standins corresponding to the big files requested by the
391 395 # user. Have to modify _files to prevent commit() from
392 396 # complaining "not tracked" for big files.
393 397 lfiles = lfutil.listlfiles(self)
394 398 match = copy.copy(match)
395 399 origmatchfn = match.matchfn
396 400
397 401 # Check both the list of largefiles and the list of
398 402 # standins because if a largefile was removed, it
399 403 # won't be in the list of largefiles at this point
400 404 match._files += sorted(standins)
401 405
402 406 actualfiles = []
403 407 for f in match._files:
404 408 fstandin = lfutil.standin(f)
405 409
406 410 # ignore known largefiles and standins
407 411 if f in lfiles or fstandin in standins:
408 412 continue
409 413
410 414 # append directory separator to avoid collisions
411 415 if not fstandin.endswith(os.sep):
412 416 fstandin += os.sep
413 417
414 418 actualfiles.append(f)
415 419 match._files = actualfiles
416 420
417 421 def matchfn(f):
418 422 if origmatchfn(f):
419 423 return f not in lfiles
420 424 else:
421 425 return f in standins
422 426
423 427 match.matchfn = matchfn
424 428 result = orig(text=text, user=user, date=date, match=match,
425 429 force=force, editor=editor, extra=extra)
426 430 # This needs to be after commit; otherwise precommit hooks
427 431 # get the wrong status
428 432 lfdirstate.write()
429 433 return result
430 434 finally:
431 435 wlock.release()
432 436
433 437 def push(self, remote, force=False, revs=None, newbranch=False):
434 438 o = lfutil.findoutgoing(self, remote, force)
435 439 if o:
436 440 toupload = set()
437 441 o = self.changelog.nodesbetween(o, revs)[0]
438 442 for n in o:
439 443 parents = [p for p in self.changelog.parents(n)
440 444 if p != node_.nullid]
441 445 ctx = self[n]
442 446 files = set(ctx.files())
443 447 if len(parents) == 2:
444 448 mc = ctx.manifest()
445 449 mp1 = ctx.parents()[0].manifest()
446 450 mp2 = ctx.parents()[1].manifest()
447 451 for f in mp1:
448 452 if f not in mc:
449 453 files.add(f)
450 454 for f in mp2:
451 455 if f not in mc:
452 456 files.add(f)
453 457 for f in mc:
454 458 if mc[f] != mp1.get(f, None) or mc[f] != mp2.get(f,
455 459 None):
456 460 files.add(f)
457 461
458 462 toupload = toupload.union(
459 463 set([ctx[f].data().strip()
460 464 for f in files
461 465 if lfutil.isstandin(f) and f in ctx]))
462 466 lfcommands.uploadlfiles(ui, self, remote, toupload)
463 467 return super(lfilesrepo, self).push(remote, force, revs,
464 468 newbranch)
465 469
466 470 repo.__class__ = lfilesrepo
467 471
468 472 def checkrequireslfiles(ui, repo, **kwargs):
469 473 if 'largefiles' not in repo.requirements and util.any(
470 474 lfutil.shortname+'/' in f[0] for f in repo.store.datafiles()):
471 475 repo.requirements.add('largefiles')
472 476 repo._writerequirements()
473 477
474 478 ui.setconfig('hooks', 'changegroup.lfiles', checkrequireslfiles)
475 479 ui.setconfig('hooks', 'commit.lfiles', checkrequireslfiles)
General Comments 0
You need to be logged in to leave comments. Login now